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]]
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]]
Sorting a Hash by Key or Value
# ==> Sorting a Hash by Key or Value (see lower)
my_hash = {'a'=>'1', 'c'=>'3', 'b'=>'2'}
my_hash.keys.sort.each do |key|
puts my_hash[key]
end
Gives:
1
2
3
# Hashes are unsorted objects because of the way in which they are stored
#internally. If you want to access a Hash in a sorted manner by key,
# you need to use an Array as an indexing mechanism as is shown above.
# You can also use the Hash#sort method to get a
# ==> new sorted Array of pairs:
my_hash.sort
#=> [["a", "1"], ["b", "2"], ["c", "3"]]
# You can do the same by value, but it’s a little more complicated:
my_hash.keys.sort_by { |key| my_hash[key] }.each do |key|
puts my_hash[key]
end
# Or, you can use the Hash#sort method for values:
my_hash.sort { |l, r| l[1]<=>r[1] }
#=> [["a", "1"], ["b", "2"], ["c", "3"]]
# This works by using the Emmuerator#sort_by method that is mixed
# into the Array of keys. #sort_by looks at the value my_hash[key] returns
# to determine the sorting order.
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]}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us