Is there something like this in ruby?
send(+, 1, 2)
I want to make this piece of code seem less redundant
if op == "+"
return arg1 + arg2
elsif op == "-"
return arg1 - arg2
elsif op == "*"
return arg1 * arg2
elsif op == "/"
return arg1 / arg2
Ruby Arithmetic OperatorsAddition − Adds values on either side of the operator. Subtraction − Subtracts right hand operand from left hand operand. Multiplication − Multiplies values on either side of the operator. Division − Divides left hand operand by right hand operand.
Triple Equals Operator (More Than Equality) Our last operator today is going to be about the triple equals operator ( === ). This one is also a method, and it appears even in places where you wouldn't expect it to. Ruby is calling the === method here on the class.
&& is logical AND operator in ruby. & is the bitwise AND operator in ruby.
It is called the Safe Navigation Operator. Introduced in Ruby 2.3. 0, it lets you call methods on objects without worrying that the object may be nil (Avoiding an undefined method for nil:NilClass error), similar to the try method in Rails.
Yup, simply use send
(or, better yet, public_send
) like so:
arg1.public_send(op, arg2)
This works because most operators in Ruby (including +
, -
, *
, /
, and more) simply call methods. So 1 + 2
is the same as 1.+(2)
.
You may also want to whitelist op
if it’s user input, e.g. %w[+ - * /].include?(op)
, as otherwise the user will be able to call arbitrary methods (which is a potential security vulnerability).
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