Andrew Haust
Andrew Haust

Reputation: 356

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

I hope I am not repeating anyone here, but I have been searching google and here and not coming up with anything. This question is really more a matter of "sexifying" my code.

What I am specifically trying to do is this:

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!

Upvotes: 6

Views: 104

Answers (3)

Asherah
Asherah

Reputation: 19347

Not in general; it's totally up to the method itself what arguments the block gets called with, and by the time each has been called (which calls your block), the fact that the string 'some_directory' was passed to Dir.new has been long forgotten, i.e. they're quite separate things.

You can do something like this, though:

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

Upvotes: 7

x1a4
x1a4

Reputation: 19475

Just break it out into a variable. Ruby blocks are closures so they will have access -

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

Upvotes: 0

Russell
Russell

Reputation: 12439

The reason it won't work is that new and each are two different methods so they don't have access to each others' parameters. To 'sexify' your code, you could consider creating a new method to contain the two method calls and pass the repeated parameter to that:

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 a low overhead means it's entirely reasonable to create one for as small a chunk of code as this - and is one of the many reasons that make Ruby such a pleasure of a language to work with.

Upvotes: 2

Related Questions