“_” parameter of Ruby block

ぐ巨炮叔叔 提交于 2019-12-06 12:44:17

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...

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!