Jay McGavren's Journal

2008-06-04

Naughty, but I like it...

Normally you can’t add objects to an array like this:

irb(main):001:0> [1] + 1
TypeError: can't convert Fixnum into Array
        from (irb):1:in `+'
        from (irb):1

But Array#+ tries to call to_ary() on its target if it’s not already an array. So just add that method, and voila:

irb(main):002:0> class Fixnum; def to_ary; [self]; end; end
=> nil
irb(main):003:0> [1] + 1
=> [1, 1]

Wait, why stop there?

irb(main):005:0> class Object; def to_ary; [self]; end; end
=> nil
irb(main):007:0> [1] + "foobar" + File.new('test.xml')
=> [1, "foobar", #<File:test.xml>]

Of course, you should probably be using Array#<< for this. But I wonder what other applications there are…

comments powered by Disqus