Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically call a math operator in Ruby?

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
like image 348
MxLDevs Avatar asked Oct 25 '12 01:10

MxLDevs


People also ask

How do you use operators in Ruby?

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.

What is the name of this operator === in Ruby?

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.

What's the difference between the & and && operators Ruby?

&& is logical AND operator in ruby. & is the bitwise AND operator in ruby.

What is the & 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.


1 Answers

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).

like image 153
Andrew Marshall Avatar answered Oct 04 '22 21:10

Andrew Marshall