Is it possible in Ruby to change an operator dynamically? Instead of having :
x y
x - y
x * y
x / y
I want to have :
operator_a =
operator_b = -
operator_c = *
operator_d = /
Example:
x = 2
y = 4
operator_a =
puts x operator_a y
I tried the example above, but it doesn't work.
CodePudding user response:
It sounds a bit pompous: you can send object x a message (operator_a) with y as argument. This is simpler than it sounds:
x = 2
y = 5
operator_a = : #or " "
puts x.send operator_a, y
CodePudding user response:
it's for a kind of calculator that will generate the operator randomly
In Ruby, operators are implemented as methods of the same name, e.g. Integer#
. You can invoke a method dynamically via send
or public_send
by passing the method's name as a symbol or string, e.g.:
2.public_send(' ', 4)
#=> 6
This is as succinct as it gets. However, when the method name is dynamic, its not clear anymore which methods will actually be invoked by that line.
Therefore (especially when working with user input) I prefer to add a little translation layer between the input and the action. So instead of passing the operator directly to send
or public_send
, I'd probably do something like this:
case operator
when ' ' then x y
when '-' then x - y
when '*' then x * y
when '/' then x / y
end
It also makes it easier to add handle situations where operators don't match, e.g. having ^
for exponentiation or adding operator variants:
case operator
when '/', '÷' then x / y
when '^' then x ** y
end