没有结束的Ruby多行块 [英] Ruby multiline block without do end

查看:51
本文介绍了没有结束的Ruby多行块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ruby 的初学者,所以很抱歉问这么简单的问题,但是这段代码有什么问题吗 –

I’m a beginner in Ruby, so I’m sorry to ask something so simple, but is there anything wrong with this code –

3.upto(9) {
  print "Hello"
  puts " World"
}

3.upto(9) { |n|
  print "Hello "
  puts n
}

它工作得很好,但我看到的大多数代码示例都使用了

It works well enough, but most of the code samples I see use the syntax of

3.upto(9) do |n|
  print "Hello "
  puts n
end

是否只是对单个语句使用花括号的惯例?来自 C/C# 第一个对我来说似乎更自然,但在罗马时!

is it just the convention to only use curly braces for single statements? Coming from C/C# the first seems more natural to me, but when in Rome!

推荐答案

这两种语法之间存在细微差别.{ } 的优先级高于 do ... end.因此,下面的代码会将 bar 和一个块传递给方法 foo:

There is a subtle difference between the two syntaxes. { } are higher precedence than do ... end. Thus, the following will pass bar and a block to method foo:

foo bar do ... end

而以下将传递一个块给bar,并将结果传递给foo:

while the following will pass a block to bar, and the result of that to foo:

foo bar { ... }

所以你的例子会起到同样的作用.但是,如果您不使用括号:

So your examples will act the same. However, if you left the parentheses off:

> 3.upto 9 { 
  puts "Hi" 
}
SyntaxError: compile error
(irb):82: syntax error, unexpected '{', expecting $end
3.upto 9 { 
          ^
    from (irb):82
    from :0

> 3.upto 9 do 
    puts "Hi" 
  end
Hi
Hi
Hi
Hi
Hi
Hi
Hi
=> 3

因此,如果您在 Ruby 中省略括号,{ } 更有可能赶上您,这很常见;出于这个原因,并且因为 Ruby 条件和其他控制结构都使用 end 作为分隔符,人们通常使用 do ... end 来表示来自声明的结尾.

So, { } are more likely to catch you up if you leave off parentheses in Ruby, which is fairly common; for this reason, and because Ruby conditionals and other control constructs all use end as a delimiter, people usually use do ... end for multi-line code blocks that come at the end of a statement.

然而,{ } 经常用于 do ... end 会很麻烦的地方,例如,如果你将几个方法链接在一起,这些方法需要块.这可以让您编写简短的一行小块,可用作方法链的一部分.

However, { } is frequently use in places where do ... end would be cumbersome, for instance, if you are chaining several methods together which take blocks. This can allow you to write short, one line little blocks which can be used as part of a method chain.

> [1,2,3].sort{|x,y| y<=>x}.map{|x| x+1}
=> [4, 3, 2]

这里有一个例子来说明这种差异:

Here's an example to illustrate this difference:

def foo arg
  if block_given?
    puts "Block given to foo"
    yield arg
  else
    puts "No block given to foo"
    arg
  end
end


def bar
  if block_given?
    puts "Block given to bar"
    yield "Yielded from bar"
  else
    puts "No block given to bar"
  end
  "Returned from bar"
end

irb(main):077:0> foo bar { |arg| puts arg }
Block given to bar
Yielded from bar
No block given to foo
=> "Returned from bar"
irb(main):078:0> foo bar do |arg| puts arg end
No block given to bar
Block given to foo
Returned from bar
=> nil

这篇关于没有结束的Ruby多行块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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