July 2011
Intermediate to advanced
400 pages
8h 46m
English
You can use the send method to call a method with the same name as the specified symbol:
send1.rb
name = "Fred" puts( name.send( :reverse ) ) #=> derF puts( name.send( :upcase ) ) #=> FRED
Although the send method is documented as requiring a symbol argument, you can also use a string argument. Or, for consistency, you could use to_sym to transform the string to a symbol and then call the method with the same name as that symbol:
name = MyString.new( gets() ) methodname = gets().chomp.to_sym #<= to_sym is not strictly necessary name.send(methodname)
Here is a working example of using send to execute a named method entered at runtime:
send2.rb
class MyString < String def initialize( aStr ) super aStr end def show puts self end def rev puts self.reverse ...
Read now
Unlock full access