Hash#keys, Hash#values order question

Let h be a Hash. Calculating the arrays

k=h.keys
v=h.values

under the assumption that h is not modified
in between, is it guaranteed that for all
indices n

h[k[n]]==v[n]

i.e. that Hash#values delivers the values
in the same order than Hash#keys delivers
the respective keys?

When playing around, I found this always
the case, but can I rely on it?

Ronald

On 8/23/07, Ronald F. [email protected] wrote:

i.e. that Hash#values delivers the values
in the same order than Hash#keys delivers
the respective keys?

When playing around, I found this always
the case, but can I rely on it?
Looks like for 1.8.6, I just had a quick look at the sources and both
use
rb_hash_foreach, just with a different extractor function.
Now I cannot be sure if some internal events like GC might change the
structure of the underlying hash that could lead to different results,
would surprise me though…

HTH
Robert

2007/8/23, Ronald F. [email protected]:

i.e. that Hash#values delivers the values
in the same order than Hash#keys delivers
the respective keys?

When playing around, I found this always
the case, but can I rely on it?

If you need them in the same order, then the safest method is to
access them in one iteration, like:

irb(main):001:0> ha={:foo=>1, :bar=>2, :baz=>3}
=> {:foo=>1, :bar=>2, :baz=>3}
irb(main):004:0> keys, values = ha.inject([[],[]]) {|(ke,va),(k,v)|
[ke << k, va << v]}
=> [[:foo, :bar, :baz], [1, 2, 3]]
irb(main):005:0> keys
=> [:foo, :bar, :baz]
irb(main):006:0> values
=> [1, 2, 3]

HTH

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs