Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string to operator

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?

like image 200
stevenspiel Avatar asked Nov 16 '13 14:11

stevenspiel


2 Answers

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]
like image 119
Arup Rakshit Avatar answered Oct 09 '22 05:10

Arup Rakshit


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]
like image 27
alex_milhouse Avatar answered Oct 09 '22 07:10

alex_milhouse