是否可以在 Ruby 中每个块都有一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10991971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to have a one line each block in Ruby?
提问by Goalie
Is there a one-line method of writing this each block in Ruby?
有没有一种用 Ruby 编写每个块的单行方法?
cats.each do |cat|
cat.name
end
I'm trying to shorten the amount of code in my project. I'm using Ruby 1.9.2.
我正在尝试缩短项目中的代码量。我正在使用 Ruby 1.9.2。
Thanks!
谢谢!
回答by tokland
Yes, you can write:
是的,你可以写:
cats.each { |cat| cat.name }
Or simply:
或者干脆:
cats.each(&:name)
Note that Enumerable#eachreturns the same object you are iterating over (here cats), so you should only use it if you are performing some kind of side-effect within the block. Most likely, you wanted to get the cat names, in that case use Enumerable#mapinstead:
请注意,Enumerable#each返回您正在迭代的相同对象(此处cats),因此您应该仅在块内执行某种副作用时才使用它。最有可能的是,您想获取猫的名字,在这种情况下,请改用Enumerable#map:
cat_names = cats.map(&:name)
回答by J?rg W Mittag
Just remove the line breaks:
只需删除换行符:
cats.each do |cat| cat.name end
Note, there are two different coding styles when it comes to blocks. One coding style says to alwaysuse do/endfor blocks which span multiple lines and alwaysuse {/}for single-line blocks. If you follow that school, you should write
请注意,当涉及到块时,有两种不同的编码风格。一个编码风格说要始终使用do/end为其跨越多行和块始终使用{/}单行块。如果你跟随那所学校,你应该写
cats.each {|cat| cat.name }
The other style is to alwaysuse do/endfor blocks which are primarily executed for their side-effects and {/}for blocks which are primarily executed for their return value. Since eachthrows away the return value of the block, it only makes sense to pass a block for its side-effects, so, if you follow that school, you should write it with do/end.
另一种风格是始终使用do/end用于主要执行其副作用的块和{/}用于主要执行其返回值的块。由于each丢弃了块的返回值,因此传递块只是为了它的副作用,所以,如果你遵循那个学校,你应该用do/编写它end。
But as @tokland mentions, the more idiomatic way would be to write
但正如@tokland 提到的,更惯用的方式是写
cats.each(&:name)
回答by Zaharije
Another trick which I use for rails console/irb is to separate commands with ';' e.g.
我用于 rails 控制台/irb 的另一个技巧是用 ';' 分隔命令 例如
[1,2].each do |e| ; puts e; end
回答by Robert SS
for cat in cats;cat.name;end
that should do it too.
那也应该这样做。

