Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash .keys and .values, safe to assume same order?

Tags:

ruby

hash

Rudimentary irb testing suggests that Ruby Hash returns .keys and .values in matching order. Is it safe to assume that this is the case?

like image 835
Finbarr Avatar asked Jul 05 '12 18:07

Finbarr


People also ask

How do you know if two Hashes are equal Ruby?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared.

Are Ruby Hashes sorted?

It would be good to see that in the question if so (then the question and answer would match). What do you want as the output? Hashes aren't really sorted (they are, by insertion order, as of Ruby 1.9+).

Can Hashes be sorted?

The hash sort is a general purpose non-comparison based sorting algorithm by hashing, which has some interesting features not found in conventional sorting algorithms. The hash sort asymptotically outperforms the fastest traditional sorting algorithm, the quick sort.

How do you combine Hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.


1 Answers

Yes. According to the Ruby Docs for Hash, "Hashes enumerate their values in the order that the corresponding keys were inserted." So you should always get the same order for a hash if it is created in the same way.

like image 127
Jonathon Jones Avatar answered Sep 24 '22 13:09

Jonathon Jones