Calling a Method From a String With the Method's Name in Ruby

BuddyJoe picture BuddyJoe · Sep 10, 2009 · Viewed 96.5k times · Source

How can I do what they are talking about here, but in Ruby?

How would you do the function on an object? and how would you do a global function (see jetxee's answer on the post mentioned)?

EXAMPLE CODE:

event_name = "load"

def load()
  puts "load() function was executed."
end

def row_changed()
  puts "row_changed() function was executed."
end 

#something here to see that event_name = "load" and run load()

UPDATE: How do you get to the global methods? or my global functions?

I tried this additional line

puts methods

and load and row_change where not listed.

Answer

Colin Gravill picture Colin Gravill · Sep 10, 2009

To call functions directly on an object

a = [2, 2, 3]
a.send("length")
# or
a.public_send("length")

which returns 3 as expected

or for a module function

FileUtils.send('pwd')
# or
FileUtils.public_send(:pwd)

and a locally defined method

def load()
    puts "load() function was executed."
end

send('load')
# or
public_send('load')

Documentation: