"对于" vs“每个”在Ruby中 [英] "for" vs "each" in Ruby
问题描述
#way 1
@ collection.each do |项目|
#做任何
结束
#方式2
在@collection中的项目
#做任何
结束
只是想知道这些是否完全一样,或者可能存在细微的差异(可能当 @collection
是nil)。
这是唯一的区别:
each:
irb> [1,2,3] .each {| x | }
$
=> [1,2,3]
irb> x
NameError:未定义的局部变量或方法`x'for main:Object $ b $ from(irb):2
from:0
$ bfor:
$ birb>对于[1,2,3]中的x;结束
=> [1,2,3]
irb> x
=> 3
通过
for
循环,迭代器变量仍然生活在块完成后。使用每个
循环,除非它在循环开始之前已经被定义为局部变量,否则它不会。
<除此之外,对于
方法来说只是
的语法糖。
当
@collection
是nil
两个循环都抛出一个异常:
例外:未定义的局部变量或方法`@collection'为main:Object
I just had a quick question regarding loops in Ruby. Is there a difference between these two ways of iterating through a collection?
# way 1 @collection.each do |item| # do whatever end # way 2 for item in @collection # do whatever end
Just wondering if these are exactly the same or if maybe there's a subtle difference (possibly when
@collection
is nil).解决方案This is the only difference:
each:
irb> [1,2,3].each { |x| } => [1, 2, 3] irb> x NameError: undefined local variable or method `x' for main:Object from (irb):2 from :0
for:
irb> for x in [1,2,3]; end => [1, 2, 3] irb> x => 3
With the
for
loop, the iterator variable still lives after the block is done. With theeach
loop, it doesn't, unless it was already defined as a local variable before the loop started.Other than that,
for
is just syntax sugar for theeach
method.When
@collection
isnil
both loops throw an exception:Exception: undefined local variable or method `@collection' for main:Object
这篇关于"对于" vs“每个”在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!