18

I have an array

operator = ['+', '-', '*', '/']

And I want to use them to solve an equation in 4 different ways. I imagine it would be something like this:

operator.map {|o| 6 o.to_sym 3 } # => [9, 3, 18, 2]

How do I do this?

vaibhavatul47
  • 2,766
  • 4
  • 29
  • 42
stevenspiel
  • 5,775
  • 13
  • 60
  • 89

2 Answers2

28

Do as below using Object#public_send method :

operator = ['+', '-', '*', '/']
operator.map {|o| 2.public_send o,2 }
# => [4, 0, 4, 1]

One more way using Object#method and Method#call:

operator = ['+', '-', '*', '/']
operator.map {|o| 2.method(o).(2) }
# => [4, 0, 4, 1]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
1

Another way to do this is by using a try. The reason try is probably preferred is that try is a more defensive version of send.

def try(*a, &b)
  if a.empty? && block_given?
    yield self
  else
    __send__(*a, &b)
  end
end

Doing this with a try would look like this:

operator = ['+', '-', '*', '/']
val_to_be_operated = nil

operator.map { |v| val_to_be_operated.try(v, 2) } 
# => [nil, nil, nil, nil]
operator.map { |o| val_to_be_operated.method(o).(2) } 
# Error

val_to_be_operated = 2 
operator.map { |v| val_to_be_operated.try(v, 2) }
# => [4, 0, 4, 1]
alex_milhouse
  • 891
  • 1
  • 13
  • 31