ruby - Ruby 的 send 和 public_send 方法有什么区别?

标签 ruby

我很好奇sendpublic_send有什么区别。例如:

class Klass
  def hello(*args)
    "Hello " + args.join(' ')
  end
end

k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
k.public_send :hello, "gentle", "readers" #=> "Hello gentle readers"

最佳答案

Unlike send, public_send calls public methods only.

Source

例子:

class Klass
  private
  def private_method
    puts "Hello"
  end
end

k = Klass.new
k.send(:private_method)
# => "Hello"

k.public_send(:private_method)
# => `public_send': private method `private_method' called for #<Klass:0x007f5fd7159a80> (NoMethodError)

您可能希望使用 #public_send 而不是 #send,以免规避私有(private)/ protected 可见性。

关于ruby - Ruby 的 send 和 public_send 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401970/

相关文章:

mysql - 为 RoR 设置 MySQL 数据库时出错

ruby - Ruby 中的正则表达式

ruby - 为什么在 ruby​​ 中动态创建大量符号不是一个好主意(对于 2.2 之前的版本)?

ruby-on-rails - Rails 项目 : NoMethodError: undefined method `identifier' for String

arrays - 二进制 ruby 计数

ruby - 如何使用 Money gem 正确兑换

ruby - 从终端解析命令

Ruby - 如何将混合数转换为 float ?

ruby - 将 .feature 文件中的变量作为数组参数传递

ruby-on-rails - Ruby on Rails 4 中的日期时间格式