Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby function as value of hash

Tags:

function

ruby

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?

like image 686
grid Avatar asked Oct 23 '12 15:10

grid


People also ask

How do I get the Hash value in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

What is Hash function in Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

What does .keys do in Ruby?

Hash#keys() is a Hash class method which gives an array with all the keys present in the hash.

How do you make Hash Hash in Ruby?

Just like arrays, hashes can be created with hash literals. Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }.


3 Answers

You could use method method.

def foo(var)
      return var + 2
end

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

hash_var[:func].call(10)
like image 197
xdazz Avatar answered Oct 13 '22 02:10

xdazz


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
like image 36
severin Avatar answered Oct 13 '22 00:10

severin


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

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

hash_var['func'].call(10) #=> 12
like image 40
John Douthat Avatar answered Oct 13 '22 00:10

John Douthat