2015-05-22 115 views
6

我很好奇,想知道有什麼區別sendpublic_send之間。例如:什麼是紅寶石的區別發送和紅寶石public_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" 

有人能解釋一下這個區別嗎?

+1

要了解@Casper手段,讓你的'hello'方法私有,然後再試一次。 – Mischa

+0

瞭解@Mischa .......非常感謝。 –

回答

10

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

與發送,public_send只調用公共方法。

例子:

class Klass 
    private 
    def m 
    puts "Hello" 
    end 
end 

k = Klass.new 
k.send(:m) 
=> "Hello" 
k.public_send(:m) 
=> `public_send': private method `m' called for #<Klass:0x007f5fd7159a80> (NoMethodError)