Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an arithmetic operator as parameter to rails method?

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(+)
like image 608
dodgerogers747 Avatar asked Dec 01 '22 21:12

dodgerogers747


2 Answers

You could use a block, and do something like

def calculate
  yield 1254,34
end
calculate &:+ # => 1288
like image 37
Luís Ramalho Avatar answered Jan 05 '23 23:01

Luís Ramalho


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.

like image 196
Platinum Azure Avatar answered Jan 06 '23 00:01

Platinum Azure