Is it possible in Ruby to get a reference to methods of an object ( I would like to know if this can be done without procs/lambdas ) , for example , consider the following code :
class X
def initialize
@map = {}
setup_map
end
private
def setup_map
# @map["a"] = get reference to a method
# @map["b"] = get reference to b method
# @map["c"] = get referebce to c method
end
public
def call(a)
@map["a"](a) if a > 10
@map["b"](a) if a > 20
@map["c"](a) if a > 30
end
def a(arg)
puts "a was called with #{arg}"
end
def b(arg)
puts "b was called with #{arg}"
end
def c(arg)
puts "c was called with #{arg}"
end
end
Is it possible to do such thing ? I would like to avoid procs/lambdas because I want to be able to change the behaviour of A,B,C by subclassing .
You can get a reference to the method by
object.method(:method_name)
.Eg: To get a reference to
system
method.You want
Object#method
:Now your code becomes:
Ruby methods aren't first-class objects; it implements OO with message passing.
Or just call them directly:
You can do this with lambdas while maintaining the ability to change behavior in subclasses: