连接每个和with_index是可以接受的吗?
问题描述:
是它最好不要级联each
并用with_index
这样连接每个和with_index是可以接受的吗?
array.each_with_index { ... }
或级联是完全可以接受的?
array.each.with_index { ... }
答
这两种形式都是正确的,将工作。然而,在列出的案例中,第一种形式是首选,因为它为此任务使用了专门构建的方法。
第二种形式通常应保留用于不与索引选项具有如在此代码傻位的方法:其具有作为输出
['a', 'b', 'c', 'd'].select.with_index {|_d, i| (i%2)==0}
:
["a", "c"]
HTTP:/ /stackoverflow.com/questions/20258086/difference-between-each-with-index-and-each-with-index-in-ruby –
请注意[Enumerator#with_index](http://ruby-doc.org/core -2.3.0/Enumerator.html#method-i-with_index)(不像[Enumerable#each_with_index](http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-ea ch_with_index))采用等于第一个索引的可选参数(默认为零)。所以,如果你希望索引从'1'开始,那么你可以写'.each.with_index(1)'而不是'.each_with_index'。如果'i'是块变量,则可以避免在块内写入'i + 1'。 –