tags:

views:

173

answers:

2

Hello,

Does anyone know if there is a way to access the names of the parameters passed in ruby blocks?

E.g.

def do_something()
  # method uses the names of the parameters passed to the block
  # in addition to their values
  # e.g. the strings "i" and "j"
end

do_something { |i, j| ... }

It's a requirement for a dsl I'm writing, and quite an unusual use case. This is probably possible with something like parsetree, I just wondered if there was an easier/cheekier way.

Thanks

+2  A: 

update: It looks like Ruby 1.9 can do what you're requesting. See Florian's answer.

Yes, well, Ruby has this great facility for passing named parameters: Hash.

Here's how it works:

def do_something(params)
  params.each do |key, value|
    puts "received parameter #{key} with value #{value}"
  end
end

do_something(:i => 1, :j => 2)

Otherwise, no there's not really a way to get the names of passed variables in Ruby. A variable in Ruby is just a reference to an Object, so there's no way to know from the Object which reference (of the potentially many references) was used in the method call.

m104
+3  A: 

This is actually possible, but only in the trunk version of 1.9:

->(a,b,c) {}.parameters

It is not released though and will most probably be included in Ruby 1.9.2.

Regards, Florian Gilcher

Skade
Yeah, it looks like this is what the poster wanted to know. Ruby 1.9 continues to impress!
m104
Note that this is only in trunk right now. It's not in 1.9.1.
Chuck
Great. Thanks for the help everyone. Looking forward to trying it out.
fturtle