“为"vs “每个"在红宝石 [英] "for" vs "each" in Ruby

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

问题描述

我刚刚有一个关于 Ruby 循环的快速问题.这两种遍历集合的方式有区别吗?

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

只是想知道这些是否完全相同,或者是否存在细微差别(可能当 @collection 为零时).

Just wondering if these are exactly the same or if maybe there's a subtle difference (possibly when @collection is nil).

推荐答案

这是唯一的区别:

每个:

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

用于:

irb> for x in [1,2,3]; end
  => [1, 2, 3]
irb> x
  => 3

使用 for 循环,迭代器变量在块完成后仍然存在.对于 each 循环,它不会,除非它在循环开始之前已经定义为局部变量.

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.

除此之外,for 只是each 方法的语法糖.

Other than that, for is just syntax sugar for the each method.

@collectionnil 时,两个循环都会抛出异常:

When @collection is nil both loops throw an exception:

异常:main:Object 的未定义局部变量或方法`@collection'

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

这篇关于“为"vs “每个"在红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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