0

I printed a collection of objects that implemented the method_missing method. The following example demonstrates this:

class Foo
  def method_missing(m, *args, &block)
    puts "missing method in #{self.class} #{m}"
    super
  end
end

bar = [Foo.new, Foo.new, Foo.new]

bar.each { |i| puts "#{i}" }
puts "====================="
bar.each { |i| puts i }
puts "====================="
Foo.new.to_ary 

Output

#<Foo:0x00000000d62ba8>
#<Foo:0x00000000d62b80>
#<Foo:0x00000000d62b58>
=====================
missing method in Foo to_ary
#<Foo:0x00000000d62ba8>
missing method in Foo to_ary
#<Foo:0x00000000d62b80>
missing method in Foo to_ary
#<Foo:0x00000000d62b58>
=====================
missing method in Foo to_ary
./missing_test.rb:6:in `method_missing': undefined method `to_ary' for #<Foo:0x00000000d61e60> (NoMethodError)
    from ./missing_test.rb:16:in `<main>'
  1. Why is to_ary called? (I think it has something to do with the way puts tries to dig down and provide some info recursively.)
  2. Why does the call to to_ary (generated as a result of puts) not generate a missing_method error? It is not supported by Foo (or Object). All my method_missing method does is print the method name and then call super, so if to_ary shows up as missing, the call to super should throw a method_missing exception, right?
nPn
  • 16,254
  • 9
  • 35
  • 58
  • @Drenmi You are right. Question 1 is a duplicate to that question. But question 2 is a new question. – sawa Jan 24 '16 at 06:10
  • @nPn In question 1, I think you mean `to_ary`. Don't you? – sawa Jan 24 '16 at 06:10
  • Quesiton 2 is answered here: http://stackoverflow.com/questions/9467395/whats-the-difference-between-to-a-and-to-ary :-) – Drenmi Jan 24 '16 at 06:12
  • @Drenmi Sorry. I think I was wrong. Both questions were probably intended to mention `to_ary`. Then, your link answers them. – sawa Jan 24 '16 at 06:20
  • sorry yes that should have been to_ary in both questions – nPn Jan 24 '16 at 13:53
  • I will keep looking but I don't see the answer to question 2 in either the link or the link in Drenmi's comment. Both the puts statement and the Foo.new.to_ary generate a call to my override of method_missing, and both should be passed to super, but only the one that came from Foo.new.to_ary actually generated the exception. – nPn Jan 24 '16 at 14:58

0 Answers0