1

In some scenario of Ruby 1.8. If I have a hash

# k is name, v is order
foo = { "Jim" => 1, "bar" => 1, "joe" => 2}
sorted_by_values = foo.sort {|a, b| a[1] <==> b[1]}
#sorted_by_values is an array of array, it's no longer a hash!
sorted_by_values.keys.join ',' 

my workaround is to make method to_hash for Array class.

class Array
  def to_hash(&block)
    Hash[*self.collect { |k, v|
      [k, v]
    }.flatten]
  end
end

I can then do the following:

sorted_by_values.to_hash.keys.join ','

Is there a better way to do this?

1 Answer 1

3

Hashes are unordered by definition. There can be no such thing as a sorted Hash. Your best bet is probably to extract the keys from the sorted array using collect and then do a join on the result

sortedByValues = foo.sort {|a, b| a[1] <==> b[1]}
sortedByValues.collect { |a| a[0] }.join ','
Sign up to request clarification or add additional context in comments.

3 Comments

Note that hashes are ordered by key insertion order in Ruby 1.9.
Dont rely on the key insertion order in 1.9, this is not a definition, its a implementation feature. If your code works with (Matz)Ruby but not with jRuby, you know what i mean :)
@Fu86: No, it's a feature of the language (confirmed by Matz). See intro of Hash's doc: ruby-doc.org/core/classes/Hash.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.