Applying an operator to a list

Hello all, I have a quick question:
Is it possible to create a Lisp style apply function with Ruby, and
would I have to use eval to create one? The function would work as
follows:

[1, 2, 3].apply(’+’.intern) # => 6
[2, 3, 4].apply(’*’.intern) # => 24

I know I could easily sum a list like so:

[1, 2, 3].inject(0) {|n, value| n + value}

So, I guess this is just a curiosity question.

···

Travis Whitton whitton@atlantic.net

But all apply does in lisp is call a function and pass it the rest of
the arguments as a list. The semantic definition of +(1,2,3) is an
entirely separate issue.

Along vaguely similar lines, take a look at
http://www.rubygarden.org/ruby?AutoMap.

martin

···

Travis Whitton whitton@atlantic.net wrote:

Hello all, I have a quick question:
Is it possible to create a Lisp style apply function with Ruby, and
would I have to use eval to create one? The function would work as
follows:

[1, 2, 3].apply(‘+’.intern) # => 6
[2, 3, 4].apply(‘*’.intern) # => 24

Hi,

[1, 2, 3].apply(‘+’.intern) # => 6
[2, 3, 4].apply(‘*’.intern) # => 24

you mean something like this?

= begin ================================================================

class Array
# Taken from PRR (I’m still using 1.6.7)
def inject(n)
each { |value| n = yield(n, value) }
n
end

# Apply func
def apply(op)
return nil if self.empty?
    self[1..-1].inject(self[0]) { |n, v| n.method(op).call(v) }
end

# Apply func without inject ...
def apply_ni(op)
    n = self[0]
    self[1..-1].each { |x| n = n.method(op).call(x) } unless \
        self.size <= 1
    n
end

end

puts (.apply(‘+’.intern)) # => nil
puts ([1].apply(‘+’.intern)) # => 1
puts ([1, 2, 3].apply(‘+’.intern)) # => 6
puts ([2, 3, 4].apply(‘*’.intern)) # => 24
puts ([“abc”, “def”].apply(‘+’.intern)) # => abcdef

= end ================================================================

Sincerely,
W.

···


Wejn <lists+rubytalk(at)box.cz>
(svamberk.net’s Linux section, fi.muni.cz student, linuxfan)

    Bored?  Want hours of entertainment?         <<<
      Just set the initdefault to 6!             <<<

you mean something like this?

Yes, that was exactly what I was looking for. I guess that I was a bit off
target as to what the Lisp apply function does, but the code you posted
has the exact behaviour I was looking for.

Thanks!
Travis Whitton whitton@atlantic.net