加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby for in循环错误与{}块定界符

发布时间:2020-12-16 22:08:28 所属栏目:百科 来源:网络整理
导读:在 Ruby语言中,以下工作在irb中 for fruit in ['apple','banana','cherry','date'] do puts fruit end 但是这个没有 # errorfor fruit in ['apple','date'] { puts fruit } 请注意参考以下块分隔符不要错误 5.times do |i| puts "hello "+i.to_send5.times {
在 Ruby语言中,以下工作在irb中
for fruit in ['apple','banana','cherry','date'] do
    puts fruit 
end

但是这个没有

# error
for fruit in ['apple','date'] { puts fruit }

请注意参考以下块分隔符不要错误

5.times do |i|
    puts "hello "+i.to_s
end

5.times { |i| puts "hello "+i.to_s }

编辑:我想我正在观察的是与…的结果不一致的替代{}有人可以解释为什么或请指出我的错误?

解决方法

以下来自 this的帖子解释了“不一致”(强调我的):

end is 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循环是控制结构 – 而不是具有块参数的方法 – 因此它们必须用end关键字关闭.诸如Enumerable#times和Enumerable#的方法每个都有一个块参数,可以用{}或者do … end语法来定义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读