2016-03-22 9 views
2

send kullanılabilir.Ruby'de gönder ve public_send yöntemlerini ne zaman kullanılır? Özel yöntemlerin yanı sıra herkese çağrı yapmak için

Örnek:

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) 

Sonra nerede ve neden public_send kullanılır?

+0

Sorum şu? public_send' –

+0

yakut ilk sürümü beri var olan send' AFAIK 'fakat' sıkı kapsülleme tercih edenler tadı karşılamak için oldukça geç tanıtıldı. – Aetherus

+0

Kamu yöntemlerini çağırmak istediğinizde ve internals ile uğraşmaya çalışmadığınızda 'public_send' işlevini kullanın. Bu şekilde amacınızı, kodunuzun gelecekteki okuyucularına iletirsiniz. –

cevap

6

Kullanım public_send dinamik bir yöntem adı anlaması ve diyoruz, henüz hala kapsülleme sorunları istemiyorum istiyorum. Başka bir deyişle

, public_send sadece doğrudan hiçbir iş arounds yöntemin çağrıyı simüle edilecek. Kapsülleme ve meta programlama karıştırma için iyidir.

Örnek: Gördüğünüz gibi

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 özel yöntem ve dolayısıyla güvenlik/kapsülleme sorunu arayacak:

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. 

giriş hi ve secret şudur

çıkışı oluşur. kamu ise public_send Oysa sadece aksi normal bir davranış (geçersiz eğer method_missing arayarak ya da bir NoMethodError yükselterek) oluşur yöntemini çağırır. send sonra özel yöntemle yanı sıra halkı çağırabilir ne zaman ve niçin public_send kullanmak eğer

İlgili konular