Ruby: why does puts call to_ary?

后端 未结 1 501
说谎
说谎 2020-12-06 17:18

I\'m learning metaprogramming in Ruby and am just trying out defining missing methods via method_missing and define_method. I\'m getting some unexpected behaviour and am won

相关标签:
1条回答
  • 2020-12-06 17:35

    puts is a synonym for $stdout.puts. $stdout is an IO class, so look at the documentation for IO.puts:

    Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line.

    This mean that puts method is intended to write several lines of output. Thus it tries to call to_ary method on an object and if to_ary is defined, then prints each element of the returned Array on a new line, else puts calls to_s method.

    to_ary internal usage is really not well documented in the Ruby documentation (Matz points this out in his The Ruby Programming Language book).

    Methods print and p on the other hand don't call to_ary, only to_s.

    Sidenote: Interesting, that to_ary must return real Array object, not an object defining each method or something else:

    class Test
      def to_ary
        10.downto(1)
      end
    end
    
    puts Test.new
    
    #TypeError: can't convert Test to Array (Test#to_ary gives Enumerator)
    #        from (irb):28:in `puts'
    #        from (irb):28:in `puts'
    #        from (irb):28
    
    0 讨论(0)
提交回复
热议问题