I wanted to take a method reference and invoke it based on certain conditions. I googled for it and i ran into this page: http://objectmix.com/ruby/332649-passing-method-references-python-ruby.html
They list numerous methods here and i’m just simply astounded
1. using send – i used this
send(method_name, args…)
2. lambda – i have yet to understand lambdas and Procs fully
algorithms = {
:first_way => lambda {|a,b| ‘Tastes great.’},
:second_way => lambda {|a,b| ‘Less filling’},
# more algorithms here…
}
# …
puts algorithms[:first_way][nil, nil]
puts algorithms[:second_way][nil, nil]
3.taking method references with method()
def firstWay(arg1, arg2)
return ‘Tastes great.’
end
def secondWay(arg1, arg2)
return ‘Less filling.’
end
def doStuff(whichway, first_arg, second_arg)
return whichway.call(first_arg, second_arg)
end
puts doStuff(method(:firstWay), nil, nil
And also, a few methods based on ‘defining classes, and methods’ in runtime, based on procs etc.
This is just too awesome.
Tags: methodreferences