Sto imparando la metaprogrammazione in Ruby e sto solo provando a definire i metodi mancanti tramite method_missing e define_method. Sto ricevendo un comportamento inaspettato e mi sto chiedendo se qualcuno possa spiegarlo. Qui è la mia classe:Ruby: perché mette la chiamata a_ary?
class X
def method_missing(m, *args, &block)
puts "method #{m} not found. Defining it."
self.class.send :define_method, m do
puts "hi from method #{m}"
end
puts "defined method #{m}"
end
end
Ora, questo codice:
x = X.new
x.some_method
puts
x.some_method
puts
puts x
produce l'output:
method some_method not found. Defining it.
defined method some_method
hi from method some_method
method to_ary not found. Defining it.
defined method to_ary
#<X:0x007fcbc38e5030>
Quello che non capisco è l'ultima parte: perché Rubino chiamando to_ary in una chiamata a mettere? Perché Ruby dovrebbe provare a convertire il mio oggetto in un array solo per stamparlo?
Googled intorno e trovato questi link correlati:
- http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/
- http://yehudakatz.com/2010/01/02/the-craziest-fing-bug-ive-ever-seen/
Questi parlano anche di method_missing e to_ary trucchi, ma non specificamente sul perché mette chiamerebbero to_ary .
Vorrei anche ricordare che il comportamento non cambia quando definisco un to_s, ad es.
def to_s
"I'm an instance of X"
end
L'uscita di "puts x" è quindi:
method to_ary not found. Defining it.
defined method to_ary
I'm an instance of X
Grazie. Penso che l'essenza sia "to_ary l'uso interno non è molto ben documentato nella documentazione di Ruby" :) Ho appena letto i documenti di IO.puts, non menzionano esplicitamente to_ary, questo dovrebbe essere più chiaro, credo. Grazie per aver segnalato il libro "The Ruby Programming Language", potresti verificarlo. –