Stefan Marbury
Stefan Marbury

Reputation: 187

Hash key as method identifier

I have some ruby code like this:

my_hash = {
  key1: "value", 
  key2: "value"
}

def key1
  do_something
end

def key2
  do_something_else
end

As you can see the keys and the methods have the same name. I now want to "convert" the hash keys into method calls where the method name is the hash key

As a background, I have an ncurses menu where the hash values are the labels and I only pass the keys around. And when a menu entry is selected I want to execute the correct method without too much coding overhead like figuring out in a if or case statement which entry was selected.

Is this possible in any way? And if yes, how can I do it?

This thing is a bit hard for me to explain and I hope you get what I mean.

Upvotes: 0

Views: 118

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 97004

Use send to call the method with the name of the symbol:

my_hash.each { |k,_| send k }

This will call all methods in the hash. You can pick out just one and call it using send as well instead of iterating.

Upvotes: 1

Related Questions