2

I met this when I read ZenTest source code:

Here is the definition of add_mapping method:

def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end

In the Autottest.initailize(), add_method get called to add mapping for implementations.

self.add_mapping(/^lib\/.*\.rb$/) do |filename, _|
  possible = File.basename(filename).gsub '_', '_?'
  files_matching %r%^test/.*#{possible}$%
end

My question is what "_", the second parameter of the block, means? Seems it is not used in the block.

Thanks

eric2323223
  • 3,518
  • 8
  • 40
  • 55

3 Answers3

6

It's an idiom used to indicate the the parameter bound to '_' is not used, even though it's required to be passed to the block/method.

example:

def blah
   yield 1,2
end

blah {|a,b|
  puts a
  # b is never used
}

compare to the identical:

blah {|a,_|
   puts a
}

Note that '_' is a perfectly legal variable name in ruby, so the two versions are identical, the following works as well:

blah {|a,_|
   puts _
}

Using '_' is nothing more than a convention like using i for counters, 'x' and 'y' or 'foo' and 'bar'.

It means you're cool because you've been dabbling with functional programming, which is, I believe, where this idiom orignates...

a2800276
  • 3,272
  • 22
  • 33
  • @a2800276, could you please show me some tutorials or resources about this "_" idiom? – eric2323223 Jan 23 '09 at 15:21
  • There aren't any tutorials, it's just an idiom, common usage. It's just a variable name like any other (I've edited the ost to make that clearer) Google 'functional programming pattern matching wildcard' if you want to check out the origin. – a2800276 Jan 23 '09 at 20:00
4
def animals
  yield "Tiger"
  yield "Giraffe"
end
animals { |_| puts "Hello, #{_}" }

Example stolen from http://en.wikibooks.org/wiki/Ruby_Programming/Ruby_Basics

As far as I can see, it's defining _ as a variable which could be referenced later on. This is just forcing ruby's hand and defining _ as to the value of whatever is yielded.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • @Radar, I could understand your example. But why "_" in my question reference the result of the block? How exactly the sequence of the add_method call is? As I understand, the "_" should be reference to the "filename" variable. – eric2323223 Jan 23 '09 at 15:14
2

Perhaps the author is using it as a short variable name so that the second parameter can be ignored.

Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238