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
Perhaps because hashes aren’t ordered, and the common semantics of “<<”
implies order.
Cheers
Dave
···
On Apr 23, 2004, at 21:49, Peña, Botp wrote:
Is there a reason why “<<” isn’t allowed for hashes?
Dave Thomas wrote:
Is there a reason why “<<” isn’t allowed for hashes?
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}>
···
On Apr 23, 2004, at 21:49, Peña, Botp wrote:
Joel VanderWerf vjoel@PATH.Berkeley.EDU writes:
Dave Thomas wrote:
Is there a reason why “<<” isn’t allowed for hashes?
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}>
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:
-
It’s a new key, so just add the key/value pair
-
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
···
On Apr 23, 2004, at 21:49, Peña, Botp wrote:
–
mike@stok.co.uk | The “`Stok’ disclaimers” apply.
http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA
mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60
http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA