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?
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With