Reputation: 375
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
Upvotes: 1
Views: 1358
Reputation: 1436
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.
Upvotes: 7
Reputation: 1136
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.
Upvotes: 2