pushing hash

P

Peña, Botp

Hi Ruby friends:

I can push thru an array fine:

irb(main):059:0> a
=> [["a", 2], ["b", 1], ["c", 3]]

irb(main):060:0> a << ["d",4]
=> [["a", 2], ["b", 1], ["c", 3], ["d", 4]]


cannot do it using hash.

irb(main):061:0> h
=> {"a"=>2, "b"=>1, "c"=>3}

irb(main):062:0> h << "d"=>4
SyntaxError: compile error
(irb):62: syntax error


irb(main):063:0> h << {"d"=>4}
NoMethodError: undefined method `<<' for {"a"=>2, "b"=>1, "c"=>3}:Hash

irb(main):064:0> h << ("d"=>4)
SyntaxError: compile error
(irb):64: syntax error

Is there a reason why "<<" isn't allowed for hashes?


kind regards -botp
 
D

Dave Thomas

Is there a reason why "<<" isn't allowed for hashes?

Perhaps because hashes aren't ordered, and the common semantics of "<<"
implies order.


Cheers

Dave
 
J

Joel VanderWerf

Dave said:
Perhaps because hashes aren't ordered, and the common semantics of "<<"
implies order.

Can't be the whole story...

irb(main):001:0> require 'set'
=> true
irb(main):002:0> Set.new << 3
=> #<Set: {3}>
 
M

Mike Stok

Joel VanderWerf said:
Can't be the whole story...

irb(main):001:0> require 'set'
=> true
irb(main):002:0> Set.new << 3
=> #<Set: {3}>

I don't think it's ordering so much as Arrays and Sets can have things
added to them "unambiguously." The Array gets the new value added to
the end, and a set gets a new member added if it doesn't already
contain the member.

When adding a key/value pair to a hash there are two situations to consider:

1) It's a new key, so just add the key/value pair

2) It's an existing key. What should we do? Replace the old
key/valur pair or somehow mutate the existing value?

If you just want to replace existing key/value pairs then

hash << ['key', 'value']

just means hash['key'] = 'value'.

Well, that's my take.

Hope this helps,

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top