11

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?

xdazz
  • 158,678
  • 38
  • 247
  • 274
grid
  • 313
  • 2
  • 8

5 Answers5

10

You could use method method.

def foo(var)
      return var + 2
end

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

hash_var[:func].call(10)
John Douthat
  • 40,711
  • 10
  • 69
  • 66
xdazz
  • 158,678
  • 38
  • 247
  • 274
4

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
severin
  • 10,148
  • 1
  • 39
  • 40
3

You can set the value to a Proc and call it.

hash_var = {
  'func' =>  proc {|x| x+2}
}

hash_var['func'].call(10) #=> 12
John Douthat
  • 40,711
  • 10
  • 69
  • 66
2

Try using lambdas

hash_var = { :func => lambda { |var| var + 2 }}
hash_var['func'].call(5) #=> 7
Raghu
  • 2,543
  • 1
  • 19
  • 24
0

Another option would be:

def foo(name)
    puts "Hi #{name}"
end

def bar(numb)
    puts numb + 1
end

hash_var = { func: :foo, func2: :bar }
send hash_var[:func], "Grid"
# => Hi Grid
send hash_bar[:func2], 3
# => 4

Here is some information about the #send method What does send() do in Ruby?

Redithion
  • 986
  • 1
  • 19
  • 32