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 end end print("Enter your name: ") #<= Enter: Fred name = MyString.new( gets() ) print("Enter a method name: " ) #<= Enter: rev methodname = gets().chomp.to_sym puts( name.send(methodname) ) #=> derF