Ruby block parameter names
Does anyone know if there is a way to access the parameter names passed in ruby blocks?
eg.
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| ... }
This is a requirement for dsl I am writing and a rather unusual use case. Maybe this is possible with something like parsetree, I was just wondering if there was an easier / leaner way.
thanks
+1
a source to share
2 answers
update . It looks like Ruby 1.9 can do what you ask. See Florian's answer.
Yes, well, Ruby has a great facility for passing named parameters: Hash.
This is 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, there is no way to get past variable names in Ruby. A variable in Ruby is just a reference to an object, so there is no way to find out from the object whose reference (potentially many references) was used in the method call.
+2
a source to share