17 ms·
because ruby does not have a separate tuple data type, so it's trivial to do so data[[v1, v2]] = something and because strings are mutable in ruby. If yo
by riffraff 14y ago
because ruby does not have a separate tuple data type, so it's trivial to do so
data[[v1, v2]] = something
and because strings are mutable in ruby.
If you couldn't use mutable objects as hash keys a bunch of things would become _way_ harder.
- masklinn 14y ago> If you couldn't use mutable objects as hash keys a bunch of things would become _way_ harder. data[[v1, v2].freeze] = something meh. Hell, Hash could even freeze its parameters on entry if they're not already frozen. Meanwhile if anybody gets a hold of the key and happens to mutate it (not necessarily for nefarious purposes, just because it solves they problem) you can quite literally lose your pair: irb(main):001:0> h = {} => {} irb(main):002:0> l = [1, 2] => [1, 2] irb(main):003:0> h[l] = 1 => 1 irb(main):004:0> h[l] => 1 irb(main):005:0> l[1] = 3 => 3 irb(main):006:0> h[l] => nil irb(main):007:0> h[[1, 2]] => nil irb(main):009:0> h[[1, 3]] => nil irb(main):010:0> h => {[1, 3]=>1} irb(main):011:0> h[[1, 3]] = 3 => 3 irb(main):012:0> h => {[1, 3]=>1, [1, 3]=>3}
- Xylakant 14y agolost your object? rehash to the rescue! jruby-1.6.8 :068 > h = {} => {} jruby-1.6.8 :069 > l = [1, 2] => [1, 2] jruby-1.6.8 :071 > h[l] = 1 => 1 jruby-1.6.8 :072 > h[l] => 1 jruby-1.6.8 :073 > h[l] = 3 => 3 jruby-1.6.8 :074 > h[l] => 3 jruby-1.6.8 :075 > l[1] = 3 => 3 jruby-1.6.8 :076 > h[l] => nil jruby-1.6.8 :077 > h.rehash => {[1, 3]=>3} jruby-1.6.8 :078 > h[l] => 3 see http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-rehash http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-rehash : Rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted, this method will reindex hsh. On one side I must admit that the behavior is a bit surprising I haven't ever encountered in the wild. It's not that easy to get hold of a hash key at a random point in the code where you don't know that it is a hash key.