在 Ruby 语言中,以下在 irb 中工作
for fruit in ['apple', 'banana', 'cherry', 'date'] do
puts fruit
end
但是这个没有
# error
for fruit in ['apple', 'banana', 'cherry', 'date'] { puts fruit }
请注意引用以下 block 分隔符不要出错
5.times do |i|
puts "hello "+i.to_s
end
5.times { |i| puts "hello "+i.to_s }
编辑:我想我观察到的是用 end 代替 { } 的方式不一致有人可以解释为什么或者请指出我的错误吗?
最佳答案
以下引自this帖子很好地解释了“不一致”(强调我的):
endis a generic keyword that ends a context (conditionals, class and module definitions, method definitions, loops and exception-catching [statements]). Curly braces are special syntax for defining blocks or Hashes.
for 循环是控制结构 - 不是带有 block 参数的方法 - 因此它们必须用 end 关键字关闭。 Enumerable#times 和 Enumerable#each 等方法有一个 block 参数,可以用 { } 或 do 定义...结束语法。
关于Ruby for in loop error with { } block delimiter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373454/