I was wondering if or how it is possible to map a function to a value of a hash.
For example:
—-Start Class————
def foo(var)
return var + 2
end
hash_var = { func => foo() }
—-End Class————–
so that I could later call
Class::hash_var["func"][10]
or
Class::hash_var["func"](10)
and that would return 12?
Functions/methods are one of the few things in Ruby that are not objects, so you can’t use them as keys or values in hashes. The closest thing to a function that is an object would be a proc. So you are best off using these…
The other answers pretty much listed all possible ways of how to put a proc into a hash as value, but I’ll summarize it nonetheless 😉
there are also different ways to evaluate procs: