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
Are there any code examples left?
New code examples in category Ruby
-
Ruby 2022-03-27 13:25:03 ruby assign value to hash
-
Ruby 2022-03-25 04:05:10 test if array empty ruby
-
Ruby 2022-03-24 19:45:17 rails update without validation
-
Ruby 2022-03-23 05:15:08 ruby hello world
-
Ruby 2022-03-23 02:40:01 rails keep all params except for some
-
Ruby 2022-03-20 06:15:08 rails hidden field default value
-
Ruby 2022-03-19 19:55:31 print things ruby
-
Ruby 2022-03-18 22:15:07 rails command line
-
Ruby 2022-03-18 08:10:03 ruby get the number of same element in array
-
Ruby 2022-03-17 02:40:17 drop rails all db