article条涉及到问题,但没有给出解决方案.

当我想要编写一个方法,并有 Select 地向它传递一个参数,该参数可以是null或????(proclambdamethodblock,?).现在我们把它叫做block,因为block是有效的.block接受一个必需的参数.该方法的一个示例和对它的调用如下:

#!/usr/bin/env ruby

def foo(&proc)
  puts "before"
  if proc
    yield "passed to proc"
  end
  puts "after"
end

def add_message(s)
  puts "from add_message #{s}"
end

foo { |s| add_message(s) }
foo

结果是:

before
from add_message passed to proc
after
before
after

太棒了但是,我想做的是能够这样称呼foo:foo(&:add_message).但我做不到.改变上面第15行,我得到:

before
./temp.rb:11:in `add_message': wrong number of arguments (given 0, expected 1) (ArgumentError)
    from ./temp.rb:6:in `foo'
    from ./temp.rb:15:in `<main>'

正如上面的文章所提到的,算术现在是-2.那么,我如何编写一个简单的方法,比如add_message,我可以用&:add_message.或在99.99%的情况下,请让我在正确的轨道上做这件事.

推荐答案

问题是Symbol#to_proc不能创建一个正确调用add_message方法的进程.

# `yield` will pass it's arguments to proc
>> :add_message.to_proc.call('passed to proc')
# => ArgumentError

这将调用'passed to proc'.add_message,因为我们的方法是在Object中定义的,当在String上调用时,它可以工作,但是它缺少必需的参数.

解决方案是制作一个proc,它可以接受与add_message方法相同的参数,并将它们传递给该方法.我们可以使用Object#method返回Method对象,该对象实现自己的to_proc,并且具有与方法相同的算术.

>> method(:add_message).to_proc.arity
=> 1

>> method(:add_message).to_proc.call('passed to proc')
from add_message passed to proc
>> foo(&method(:add_message))
before
from add_message passed to proc
after

Ruby相关问答推荐

当bsearch将数组中的第一个元素与2个值匹配时,它返回nil.为什么?

VS Code Prettier 打破哈希访问

判断一个数组是否是Ruby中另一个数组的子集

C# 中的 typeof 保留字是否有 Ruby 类似功能?

如何在 Ruby 中合并多个哈希?

each_with_index_do 从 1 开始索引

在 Ruby 中创建数字、字符串、数组或哈希的 md5 哈希

Ruby 中的关联数组

Vim 用 ruby​​ 语法高亮显示很慢

扩展self 和module_function一样吗?

获取Ruby中数组的差异

Ruby 和您必须使用 OpenSSL 支持重新编译 Ruby 或更改 Gemfile 中的源代码

require File.expand_path(..., __FILE__) 是最佳实践吗?

如何在Ruby中对数组中对象的属性求和

获取类中声明的所有实例变量

我的Ruby在哪里?

Ruby 方法to_sym有什么作用?

如何在 IRB 中重新加载脚本?

将哈希传递给函数 ( *args ) 及其含义

如何判断一个类是否已定义?