"对于" vs“每个”在Ruby中 [英] "for" vs "each" in Ruby

查看:116
本文介绍了"对于" vs“每个”在Ruby中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在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


$ b

for:
$ b

  irb>对于[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 the each 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 the each method.

When @collection is nil both loops throw an exception:

Exception: undefined local variable or method `@collection' for main:Object

这篇关于&QUOT;对于&QUOT; vs“每个”在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆