Ruby 如何使用';do';关键词语法?

Ruby 如何使用';do';关键词语法?,ruby,syntax,higher-order-functions,Ruby,Syntax,Higher Order Functions,使用数组时。每个可以用两种形式指定函数: 花括号: a = [1,2,3] a.each { |x| puts x * x } a = [1,2,3] a.each do |x| puts (x * x) end def PutWith2Arg(proc) puts proc.call(2) end PutWith2Arg(Proc.new { |x| x + 100 }) 输出: 1 4 9 => [1, 2, 3] 'do'语法: a = [1,2,3] a.

使用
数组时。每个
可以用两种形式指定函数:

花括号:

a = [1,2,3]
a.each { |x| puts x * x }
a = [1,2,3]
a.each do |x|
    puts (x * x)
end
def PutWith2Arg(proc)
    puts proc.call(2)
end

PutWith2Arg(Proc.new { |x| x + 100 })
输出:

1
4
9
=> [1, 2, 3]
'do'语法:

a = [1,2,3]
a.each { |x| puts x * x }
a = [1,2,3]
a.each do |x|
    puts (x * x)
end
def PutWith2Arg(proc)
    puts proc.call(2)
end

PutWith2Arg(Proc.new { |x| x + 100 })
输出:

1
4
9
=> [1, 2, 3]
问题: 如何用自己的自定义函数复制“do”语法样式?我能得到的最接近花括号样式是:

我所尝试的:

a = [1,2,3]
a.each { |x| puts x * x }
a = [1,2,3]
a.each do |x|
    puts (x * x)
end
def PutWith2Arg(proc)
    puts proc.call(2)
end

PutWith2Arg(Proc.new { |x| x + 100 })
输出:

102
=> nil

do | foo | end
{foo | |…}
语法是等价的。这些是Ruby中的“块”,任何方法都可以获得它们。要给他们打电话,您需要:

def my_method               # No need to declare that the method will get a block
  yield(42) if block_given? # Pass 42 to the block, if supplied
end

my_method do |n|
  puts "#{n} times 2 equals #{n*2}"
end
#=> "42 times 2 equals 84"

my_method{ |n| puts "#{n} times 2 equals #{n*2}" }
#=> "42 times 2 equals 84"

my_method # does nothing because no block was passed
或者,对于更复杂的用途:

def my_method( &blk ) # convert the passed block to a Proc named blk
  blk.call( 42 ) if blk
end

# Same results when you call my_method, with or without a block
当需要将块传递给另一个方法时,后一种样式很有用。如果变量引用了Proc或Lambda,则可以使用
&
语法将其作为该方法的块传递给方法:

def my_method( &blk )   # convert the passed block to a Proc named blk
  [1,2,3].each( &blk )  # invoke 'each' using the same block passed to me
end
my_method{ |x| p x=>x**2 }
#=> {1=>1}
#=> {2=>4}
#=> {3=>9}    
关于更多细节,这是相当有启发性的