Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 将块传递给方法的替代样式?_Ruby - Fatal编程技术网

Ruby 将块传递给方法的替代样式?

Ruby 将块传递给方法的替代样式?,ruby,Ruby,当您以这种方式将块传递给方法时,调用什么:.map(&:capitalize) 只是糖吗?速记你还能用它做些什么吗?Ruby中的每个方法都有一个特殊的“块”槽,它不是一个普通的参数。这是因为将一个块精确地传递给一个方法是最常见的用例,Ruby优化了它。&符号用于表示特定于该槽内的某物的通过 def with_regular_argument(block) block.call end def with_block_argument(&block) block.call end

当您以这种方式将块传递给方法时,调用什么:
.map(&:capitalize)


只是糖吗?速记你还能用它做些什么吗?

Ruby中的每个方法都有一个特殊的“块”槽,它不是一个普通的参数。这是因为将一个块精确地传递给一个方法是最常见的用例,Ruby优化了它。
&
符号用于表示特定于该槽内的某物的通过

def with_regular_argument(block)
  block.call
end

def with_block_argument(&block)
  block.call
end

with_regular_argument lambda { puts 'regular' }    # regular
with_block_argument { puts 'block argument' }      # block argument
调用方法时也可以使用该符号。这样,您可以将任何对象作为块传递,并对其调用
to_proc
,以便将其强制为
proc

def to_proc
  proc { puts 'the main object was converted to a Proc!' }
end

with_block_argument &self    # the main object was converted to a Proc!
请注意,如果您使用\u regular\u参数调用
,则不会执行强制:

begin
  with_regular_argument self
rescue => error
  puts error.message            # undefined method `call' for main:Object
end
Symbol
类实现了
to\u proc
。它基本上是这样工作的:

class Symbol
  def to_proc
    proc { |receiver| receiver.send self }
  end
end
那么,下面这一行是如何工作的呢

enumerable.map &:to_s
  • 我们正在将
    :传递到特殊块插槽中的\u s
    。这由
    表示
  • 使用
    &
    调用
    对符号进行处理
  • to_proc
    返回一个
    proc
    ,它将
    :to_s
    发送到第一个参数
  • 然后将该
    Proc
    传递到特殊块槽中的
    map
    方法
  • 产生的每个元素都成为消息的接收者
  • 这相当于:

    enumerable.map { |receiver| receiver.send :to_s }
    

    1耶胡达·卡茨Ruby不是一种可调用的面向对象语言(它是面向对象的)