Answers for "ruby hash sort"

2

ruby reorder keys in hash

# First thing to note that #sort/#sort_by will return a new array. Therefore, if we want to return the sorted hash in hash format, we need to call #to_h after #sort.

hash = { a:1, bb:2, ccc:4, dddd:3, eeeee:2}

# sort on key in decending order
puts hash.sort_by {|k, v| -k.length }.to_h
> {:eeeee=>2, :dddd=>3, :ccc=>4, :bb=>2, :a=>1}

# you could do any thing to determine the sort order of the key this way


# a normal sort would work like this (in Ruby 2.1 or higher):
hash.sort.to_h
Posted by: Guest on June-18-2020
1

sort hash ruby

people = {
  :fred => 23,
  :joan => 18,
  :pete => 54
}

# First option
people.values.sort    # => [18, 23, 54]

# Seconf option
people.sort_by { |name, age| age }
  # => [[:joan, 18], [:fred, 23], [:pete, 54]]
Posted by: Guest on March-22-2021
1

sort array of hashes ruby

classes = [{
  start_date_time: Wed, 07 Jul 2021 12:52:20 +0000
}]

sorted_classes = classes.sort_by {|sc| sc[:start_date_time]}
Posted by: Guest on July-07-2021

Browse Popular Code Answers by Language