1. 5
  1.  

  2. 6

    Notably missing from the article (probably, because it is called “everything you should know about Ruby splats”): Ruby being Ruby, splat behaviour can be overloaded…

    class MyClass < Struct.new(:a, :b, :c)
      def to_splat
        [a, b, c]
      end
    end
    
    def insplat(*splatted)
      puts splatted.inspect
    end
    
    m = MyClass.new(1, 2, 3)
    insplat(*m)
    # => [1, 2, 3]
    
    1. 5

      What version of Ruby is that? I don’t think your example is valid - I think what’s going on there is that Struct implements #to_a

      class Bar
        def initialize(x, y)
          @x, @y = x, y
        end
      
        def to_splat
          [@y, @x]
        end
      end
      def things(one, two); puts "#{one} #{two}" end
      
      things(*Bar.new(2, 1)) # => ArgumentError: wrong number of arguments (given 1, expected 2)
      
      class Bar; def to_a; to_splat end end
      things(*Bar.new(2, 1)) # => nil
      1 2
      
      1. 5

        Hah, how embarassing. It seems to have gone. It’s documented in “The Ruby Programming Language” (Flanagan, Matsumoto).

        Here’s the commit introducing it, I can’t find the one that removes it…

        https://github.com/ruby/ruby/commit/9317700a5dc77053b84180456fa0ae10a3d33218

        And the docs where I got it from:

        http://www.eigenclass.org/hiki/ChangesinRuby1.9#l13

        Should have checked if the method is called…

        Thanks for the correction!

        1. 4

          That’s a neat piece of Ruby history/trivia! Thanks for digging up the references.

          I should mention that my initial intuition was that it was using #to_ary so I get a small sense of validation knowing that it used to be that! Very curious that splatting has changed over time like that without many people noticing.

          1. 3

            There’s this time from Ruby 1.9.0 to 1.9.3 where Ruby 1.9 was kinda there, but more in a soul-searching phase. You could port things to it and it was mostly stable, but there was also not a lot of adoption and people wouldn’t be pressured to switch. It was probably my most intense Ruby-learning time, as I was running nightly builds all the time to see what worked already and ported old stuff over.

            I assume that it was introduced during that time and subsequently removed.

        2. 2

          To clarify: splat calls the explicit array conversion method (to_a) if it’s defined and falls back to the implicit conversion (to_ary) if it’s not.