推荐答案
在 Ruby 中,调用方法的方式主要有以下几种:
直接调用方法:
object.method_name(arguments)
使用
send方法:object.send(:method_name, arguments)
使用
public_send方法:object.public_send(:method_name, arguments)
使用
method方法获取方法对象后调用:method_obj = object.method(:method_name) method_obj.call(arguments)
使用
&符号将方法作为块传递:[1, 2, 3].map(&object.method(:method_name))
本题详细解读
直接调用方法
这是最常见的调用方法的方式。你只需要在对象后面加上 . 和方法名,然后传递所需的参数即可。例如:
"hello".upcase # 返回 "HELLO"
使用 send 方法
send 方法允许你动态调用方法。你可以将方法名作为符号或字符串传递给 send,并传递相应的参数。例如:
"hello".send(:upcase) # 返回 "HELLO"
使用 public_send 方法
public_send 方法与 send 类似,但它只能调用对象的公共方法,不能调用私有或受保护的方法。例如:
"hello".public_send(:upcase) # 返回 "HELLO"
使用 method 方法获取方法对象后调用
method 方法返回一个 Method 对象,你可以通过 call 方法来调用它。这种方式适用于需要将方法作为对象传递的场景。例如:
upcase_method = "hello".method(:upcase) upcase_method.call # 返回 "HELLO"
使用 & 符号将方法作为块传递
你可以使用 & 符号将方法作为块传递给其他方法。这种方式常用于将方法作为回调传递给迭代器。例如:
["hello", "world"].map(&:upcase) # 返回 ["HELLO", "WORLD"]