Is it possible to pass an arithmetic operator ( *, +, -, /) as a parameter to a ruby method? I have seen this performed in C++. Is rails capable of something similar?
def calculate(operator)
1254 operator 34
end
puts calculate(+)
You could use a block, and do something like
def calculate
yield 1254,34
end
calculate &:+ # => 1288
Use Object#send
:
def calculate(op)
1254.send(op, 34)
end
puts calculate(:+)
This works for any method, including the defined arithmetic operators. Note that you need to send the method name as a symbol or string.
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