两种语法之间有微妙的差别。{ }
的优先级高于do ... end
。 因此,以下代码将传递bar
和一个块给方法foo
:
foo bar do ... end
下面的代码将向 bar
传递一个块,并将其结果传递给 foo
:
foo bar { ... }
所以你的例子将会表现相同。不过,如果你省略了括号:
> 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
来表示多行代码块。
然而,{ }
经常用于使用 do ... end
会很麻烦的地方,例如,如果您需要将几个需要带有块的方法链接在一起。 这可以让您编写短小的一行代码块,这些块可以作为方法链的一部分使用。
> [1,2,3].sort{|x,y| y<=>x}.map{|x| x+1}
=> [4, 3, 2]
这里有个例子可以说明它们之间的区别:
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
each
works with brackets but not withdo
-end
(ruby),Block definition - difference between braces anddo
-end
?,Usingdo
block vs brackets{}
,What is the difference or value of these block coding styles in Ruby?和Ruby block and unparenthesized arguments的副本。 - Jörg W Mittag