for循环的用法?

时间:2013-12-21 20:30:23

标签: ruby for-loop iterator

大多数时候,当我看到Ruby中使用的for循环时,编写它的人并不熟悉Ruby。通常,当for循环被迭代器替换为each等块时,它更具可读性。

是否存在使用块的迭代器无法轻易重写for的用例,或者使用for是否有优势?

for是否比迭代器方法更快,因为for是一个关键字? for的目的是什么?

2 个答案:

答案 0 :(得分:4)

我在6到8年前在Rails书籍中看到了for循环。但不再是首选。

迭代器变量的范围有所不同。请看以下示例:

numbers = [1, 2, 3]

numbers.each do |n|
  # do nothing
end
begin
  puts n 
rescue Exception => e
  puts e.message
end

for n in numbers do 
  # do nothing
end
puts "still: #{n}"

那将有这个输出:

# undefined local variable or method `n' for main:Object
# still: 3

答案 1 :(得分:2)

Ruby社区通常首选块语法。

使用foreach时,变量范围存在细微差别。 在for循环内声明的变量将在循环外部可用,其中each块中的变量是块的本地变量,并且在其外部不可用。