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

时间:2015-05-22 16:47:22

标签: ruby

我很想知道sendpublic_send之间的区别。 E.g:

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"

有人可以解释一下这个区别吗?

1 个答案:

答案 0 :(得分:28)

http://apidock.com/ruby/Object/public_send

  

与send不同,public_send仅调用公共方法。

示例:

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)