tags:

views:

39

answers:

2

Perhaps this just sounds ridiculous but I'm wondering is this possible with Ruby? Basically I have a function...

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

I'd like to be able to pass the "+" or another operator e.g "-" to the function so that it'd be something like...

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

is this possible?

+1  A: 
4.send("+", 5)

Returns 9

http://corelib.rubyonrails.org/classes/Object.html#M001077

Nikita Rybak
+4  A: 

Two possibilities:

Take method/operator name as a symbol:

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

Or the more general solution: Take a block:

def sum a,b
  yield a,b
end
sum 42, 23, &:+
sepp2k
+1 for nice usage of Symbol#to_proc
Swanand