How to find argument variable names passed to a block

I am trying to do metaprogramming and would like to know the names of the variables passed as block arguments:

z = 1 # this variable is still local to the block   

Proc.new { |x, y| local_variables }.call

# => ['_', 'z', x', 'y']

I'm not quite sure how to distinguish between variables defined outside the block and the arguments of the block in this list. Is there any other way to reflect this?

+3
source share
2 answers

Here's how you can say in Ruby 1.8:

>> z = 1
=> 1
>> Proc.new{|x| "z is #{defined? z}, x is #{defined? x}"}.call(1)
=> "z is local-variable, x is local-variable(in-block)"

but watch out! this does not work in Ruby 1.9 - you will get

=> "z is local-variable, x is local-variable"

and then I do not know the answer.

+3
source

As for the ruby ​​1.9 solution, I'm not 100% sure, but ruby ​​1.9.2 adds the method parameter method #, which returns params in an array of characters:

irb(main):001:0> def sample_method(a, b=0, *c, &d);end
=> nil
irb(main):002:0> self.method(:sample_method).parameters
=> [[:req, :a], [:opt, :b], [:rest, :c], [:block, :d]]

, .

+1

Source: https://habr.com/ru/post/1721261/


All Articles