- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
send
可用于调用公共(public)和私有(private)方法。
例子:
class Demo
def public_method
p "public_method"
end
private
def private_method
p "private_method"
end
end
Demo.new.send(:private_method)
Demo.new.send(:public_method)
那么在哪里以及为什么要使用 public_send
?
最佳答案
当你想动态推断一个方法名并调用它时,使用 public_send
,但仍然不希望有封装问题。
换句话说,public_send
只会直接模拟方法的调用,没有解决方法。它有利于混合封装和元编程。
例子:
class MagicBox
def say_hi
puts "Hi"
end
def say_bye
puts "Bye"
end
private
def say_secret
puts "Secret leaked, OMG!!!"
end
protected
def method_missing(method_name)
puts "I didn't learn that word yet :\\"
end
end
print "What do you want met to say? "
word = gets.strip
box = MagicBox.new
box.send("say_#{word}") # => says the secret if word=secret
box.public_send("say_#{word}") # => does not say the secret, just pretends that it does not know about it and calls method_missing.
当输入为 hi
和 secret
时,这是输出:
What do you want met to say? hi
=> Hi
=> Hi
What do you want met to say? secret
=> Secret leaked, OMG!!!
=> I didn't learn that word yet :\\
如您所见,send
将调用私有(private)方法,因此会出现安全/封装问题。而 public_send
只会调用方法,如果它是公共(public)的,否则会发生正常行为(调用 method_missing
如果被覆盖,或引发 NoMethodError
)。
关于ruby - 什么时候在 ruby 中使用 send 和 public_send 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36152692/
Tldr:我正在尝试使用 public_send 来调用方法,但其中一些方法也需要参数。如何检查哪些需要参数并将它们添加为参数并将它们包含在调用中 我在这样的类中有一组方法 class_methods
我正在尝试使用元编程构建一个通用方法,它使用 array 中的操作 method 并使用 send 到对象 splat,以下是工作片段: ALLOWED_DATA_TYPES = { 'Integ
我很好奇send和public_send有什么区别。例如: class Klass def hello(*args) "Hello " + args.join(' ') end end
send 可用于调用公共(public)和私有(private)方法。 例子: class Demo def public_method p "public_method" end
我是一名优秀的程序员,十分优秀!