带有自定义方法的符号#to_proc

gar*_*oat 5 ruby

我喜欢在Ruby中如何使用Symbol#to_proc以下方法将方法作为块传递:

[1.0, 2.0, 3.0].map(&:to_i)
#=> [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

我也可以定义自己的lambda,times_two并将其作为块传递:

times_two = ->(x) {x * 2}

[1, 2, 3].map(&times_two)
#=> [2, 4, 6]
Run Code Online (Sandbox Code Playgroud)

虽然我似乎不能times_two作为象征传递:

[1, 2, 3].map(&:times_two)
#=> ArgumentError: wrong number of arguments (0 for 1)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用方法执行相同操作时,我收到错误:

def times_three(x)
  x * 3
end

[1, 2, 3].map(&times_three)
#=> ArgumentError: wrong number of arguments (0 for 1)

[1, 2, 3].map(&:times_three)
#=> ArgumentError: wrong number of arguments (0 for 1)
Run Code Online (Sandbox Code Playgroud)

我猜我不能这样做因为times_three是一种方法,而不是Proc.

那么如何定义自定义方法以便Symbol#to_procto_i上面第一个例子中那样使用它们呢?

例如,我该怎么做?

[1, 2, 3].map(&:times_three)
#=> [3, 6, 9]
Run Code Online (Sandbox Code Playgroud)

编辑:我观看了下面发布的视频,显然你可以使用以下method方法接近Symbol#to_proc :

def times_three(x)
  x * 3
end

t_three = method(:times_three)
[1, 2, 3].map(&t_three)
#=> [3, 6, 9]
Run Code Online (Sandbox Code Playgroud)

但是,它不是符号#to_proc:

[1, 2, 3].map(&:t_three)
#=> NoMethodError: undefined method `t_three' for 1:FixNum
Run Code Online (Sandbox Code Playgroud)

Ste*_*zyn 5

class Integer
  def times_three
    return self * 3
  end
end
Run Code Online (Sandbox Code Playgroud)

现在,因为times_three现在是Integer类的一个方法,你可以做符号来处理...

[1, 2, 3].map(&:times_three)
Run Code Online (Sandbox Code Playgroud)

如果要访问不属于对象类但作用于对象的方法,则需要将该对象作为参数传递给方法...

def times_three(x)
  x * 3
end

[1, 2, 3].map{|i| times_three(i) }
Run Code Online (Sandbox Code Playgroud)

symbol to proc需要使用的对象作为一个接收器.

[1, 2, 3].map(&:some_action)
Run Code Online (Sandbox Code Playgroud)

相当于

[1, 2, 3].map{|i| i.some_action}
Run Code Online (Sandbox Code Playgroud)