Ruby function as value of hash

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 ;)

hash = {}

hash['variant1'] = Proc.new {|var| var + 2}
hash['variant2'] = proc     {|var| var + 2}
hash['variant3'] = lambda   {|var| var + 2}

def func(var)
  var + 2
end

hash['variant4'] = method(:func) # the *method* method returns a proc
                                 # describing the method's body 

there are also different ways to evaluate procs:

hash['variant1'].call(2) # => 4
hash['variant1'][2]      # => 4
hash['variant1'].(2)     # => 4

You could use method method.

def foo(var)
      return var + 2
end

hash_var = { :func => method(:foo) }

hash_var[:func].call(10)

Tags:

Ruby

Function