I’m looking at Page 39 of Why’s (poignant) Guide to Ruby (
http://www.rubyinside.com/media/poignant-guide.pdf ) and I see
[:shape => ‘sock’, :fabric => ‘cashmere’] +
[:shape => ‘mouse’, :fabric => ‘calico’] +
[:shape => ‘eggroll’, :fabric => ‘chenille’]
The result of this is (irb 1.9.2)
irb(main):001:0> kitty_toys =
irb(main):002:0* [:shape => ‘sock’, :fabric => ‘cashmere’] +
irb(main):003:0* [:shape => ‘mouse’, :fabric => ‘calico’] +
irb(main):004:0* [:shape => ‘eggroll’, :fabric => ‘chenille’]
=> [{:shape=>“sock”, :fabric=>“cashmere”}, {:shape=>“mouse”,
:fabric=>“calico”}, {:shape=>“eggroll”, :fabric=>“chenille”}]
irb(main):024:0> kitty_toys.size
=> 3
That is, it is an array of 3 hashes
But the lexically similar
irb(main):001:0> x=
irb(main):002:0* [1, :fabric => ‘cashmere’] +
irb(main):003:0* [2, :fabric => ‘calico’] +
irb(main):004:0* [3, :fabric => ‘chenille’]
=> [1, {:fabric=>“cashmere”}, 2, {:fabric=>“calico”}, 3,
{:fabric=>“chenille”}]
irb(main):005:0> x.size
=> 6
produces what is to me a surprisingly different result.
Clearly, ruby has flattened things for x and yet … it seems to have
kept the hashes together for kitty_toys
I would have expected
irb(main):006:0> y = [[1, {:fabric=>“cashmere”}], [2,
{:fabric=>“calico”}], [3, {:fabric=>“chenille”}]]
=> [[1, {:fabric=>“cashmere”}], [2, {:fabric=>“calico”}], [3,
{:fabric=>“chenille”}]]
irb(main):007:0> y.size
=> 3
In fact, the more I stare at it, the more I think that the correct
syntax should be
doggy_toys =
[{:shape => ‘sock’, :fabric => ‘cashmere’}] +
[{:shape => ‘mouse’, :fabric => ‘calico’}] +
[{:shape => ‘eggroll’, :fabric => ‘chenille’}]
Why is the kitty_toys syntax even legal?
I see that using the new 1.9 syntax for creating hash tables also works
the same way.
irb(main):018:0> birdy_toys =
irb(main):019:0* [shape:‘sock’, fabric:‘cashmere’] +
irb(main):020:0* [shape:‘mouse’, fabric:‘calico’] +
irb(main):021:0* [shape:‘eggroll’, fabric:‘chenille’]
=> [{:shape=>“sock”, :fabric=>“cashmere”}, {:shape=>“mouse”,
:fabric=>“calico”}, {:shape=>“eggroll”, :fabric=>“chenille”}]
irb(main):022:0> doggy_toys == birdy_toys
=> true
So what are the rules for “implied hash table”? Where would I find that
documented?
Ralph S.