Is it possible to refer to the parameter passed to the method in the passed block in ruby?

I hope Iโ€™m not repeating anyone here, but I searched Google here, and didnโ€™t invent anything. This question is really more important for the "decomposition" of my code.

What I'm specifically trying to do is the following:

Dir.new('some_directory').each do |file| # is there a way to refer to the string 'some_directory' via a method or variable? end 

Thanks!

+6
source share
3 answers

Not in general; it completely depends on the method itself, which arguments the block was called to, and by the time each was called (which calls your block), the fact that the string 'some_directory' was passed to Dir.new has long been forgotten, i.e. they are completely different.

You can do something like this:

 Dir.new(my_dir = 'some_directory').each do |file| puts "#{my_dir} contains #{file}" end 
+7
source

The reason it will not work is because new and each are two different methods, so they do not have access to each other's parameters. To โ€œdevelopโ€ your code, you might consider creating a new method that would contain two method calls and pass it a repeating parameter:

 def do_something(dir) Dir.new(dir).each do |file| # use dir in some way end end 

The fact that creating a new method has such low overhead means that it is quite reasonable to create one for such a small piece of code as this, and this is one of many reasons why Ruby is so nice to use the language with.

+2
source

Just decompose it into a variable. Ruby blocks are private, so they will have access -

 dir = 'some_directory' Dir.new(dir).each do |file| # use dir here as expected. end 
0
source

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


All Articles