1

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

3
  • I need access to the parameter names for a dsl I'm writing. Commented May 20, 2009 at 9:02
  • 1
    Can you give an example (maybe expand the question text?) of what problem is causing you to ask this? I'm kind of concerned that you may be trying to bend the block declaration syntax into a shape that it won't take... AFAIK it's not possible, but you may be able to get where you want another way. Commented May 20, 2009 at 10:51
  • In addition to what is said above, the first thing that springs to mind is Kernel#local_variables which can be used to get the names of locally declared variables. In your case I think it has to be called from within the proc/block though. Commented May 20, 2009 at 15:01

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.