Calling different method depending upon variable's value without having an if-else block in Ruby

StackOverflow https://stackoverflow.com/questions/23314586

  •  10-07-2023
  •  | 
  •  

Question

I have a variable name which can have one of the three different values: "name1" or "name2" or "name3". Depending upon different value, I have to call a different value. For "name1", I need to call method_name1,for "name2", I need to call method_name2 and similarly for "name3", I need to call method_name3.

Currently, I do it like this:

if(name == "name1")
  output = method_name1(name)
elsif(name == "name2")
  output = method_name2(name)
elsif(name == "name3")
  output = method_name3(name)
end

Instead of having if-elses, how can I have a map of methods to apply? How to do it in Ruby?

Was it helpful?

Solution

method_map = { 'name1' => :method_name1,
               'name2' => :method_name2,
               'name3' => :method_name3}

send(method_map[name])

If the name is the actual method name, you could simply

send(name)

and if you can calculate method_name from name you could try:

send("method_#{name}")

If these methods have arguments - simply add them to the send method:

send(name, some, other, args)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top