Re: Dispatching when function name is stated as a symbol



On 8/31/07, Ronald Fischer <ronald.fischer@xxxxxxxxxx> wrote:
Can someone point out an elegant way to solve the following problem?

I have a module with a function f and additional functions g1, g2, ...,
which basically looks like this:

module M
def f(&cb)
...
x=cb.call
# DO SOMETHING .... see below
end
def g1(a,b,c)
...
end
def g2(d,e)
...
end
# etc
end

The DO SOMETHING part looks like this: The proc object being called
is supposed to return an array, where the first element is a symbol
corresponding to one of the function names g1, g2 ...., and the
remaining array elements corresponding to the parameters of this
function. Hence, if
x=cb.call
causes x to contain [:g2, 25, 'dummy'], I would like to execute
g2(25,'dummy')

I have not found a convincing way of doing this.

Would this work for you?

def f(&cb)
x=cb.call
name = x[0]
args = x[1..-1]
send(name, *args);
end

def g1(a,b,c)
puts "g1: #{a}, #{b}, #{c}"
end

def g2(d,e)
puts "g1: #{a}, #{b}, #{c}"
end

irb(main):017:0> f {[:g1, 1, 2, 3]}
g1: 1, 2, 3
=> nil
irb(main):018:0> f {[:g2, 1, 2, 3]}
g2: 1, 2, 3
=> nil

Hope this helps,

Jesus.

.



Relevant Pages

  • Re: implementing the "each" method for own classes
    ... >> def each ... >> yield node.content ... > You are missing the first element. ... That's only true if head is nil for an empty queue. ...
    (comp.lang.ruby)
  • Re: implementing the "each" method for own classes
    ... otherwise nil could be returned. ... > def each ... > yield node.content ... You are missing the first element. ...
    (comp.lang.ruby)
  • Re: Sorting arrays
    ... I'm looking in particular, def recursive_sort. ... passed into def sort which immediately puts it into the ... the first element of the unsorted array and putting it into sorted. ... lowest = nil ...
    (comp.lang.ruby)
  • Dispatching when function name is stated as a symbol
    ... def g1 ... is supposed to return an array, where the first element is a symbol ... remaining array elements corresponding to the parameters of this ... together a string containing the function call. ...
    (comp.lang.ruby)
  • Re: Question on optional method parameters
    ... def enter_territory(country, depot, *rest) ... rest!= nil ... to the first element of the argument array, but I would like to pass ...
    (comp.lang.ruby)