Passing an operator to a function?

It may just sound funny, but I wonder if it is possible with Ruby? Basically, I have a function ...

def add a,b
 c = a + b
 return c
end

I would like to be able to pass "+" or another operator, for example "-", into a function, so that it is something like ...

def sum a,b,operator
 c = a operator b
 return c
end

Is it possible?

+5
source share
2 answers

Two possibilities:

Take the name of the method / operator as a symbol:

def sum a,b,operator
 a.send(operator, b)
end
sum 42, 23, :+

Or a more general solution: Take a block:

def sum a,b
  yield a,b
end
sum 42, 23, &:+
+10
source

All Articles