gpt4 book ai didi

ruby - 什么时候在 ruby​​ 中使用 send 和 public_send 方法?

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:13 55 4
gpt4 key购买 nike

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.

当输入为 hisecret 时,这是输出:

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/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com