Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

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
Comment

PREVIOUS NEXT
Code Example
Ruby :: create table if not exist rails 
Ruby :: run rake task in rails console 
Ruby :: eager load polymorphic rails 
Ruby :: authrenticate to artifactory grails 2.1.1 
Ruby :: travis ci NameError: uninitialized constant SimpleCov 
Ruby :: rails task arguments 
Ruby :: ruby reference a file in a gem 
Ruby :: rspec add support folder 
Ruby :: rails form select 
Ruby :: Your Ruby version is 3.0.0, but your Gemfile specified 2.7.4 
Ruby :: http request ruby 
Ruby :: rails find_by order limit 
Ruby :: iterate over each key value in hash ruby 
Ruby :: ruby get decimal 
Ruby :: how to generate a controller in rails 
Ruby :: ruby extract number from string 
Ruby :: times ruby 
Ruby :: rails validates_presence_of 
Ruby :: rails parse boolean 
Ruby :: pg_ctl: no database directory specified and environment variable PGDATA unset 
Ruby :: ruby map hash 
Ruby :: ruby for 
Ruby :: including libraries in ruby 
Ruby :: rails g controller with actions 
Ruby :: rails bootstrap background image 
Ruby :: ruby rspec change matcher 
Ruby :: ruby block_given? method 
Ruby :: how to know current schema database in rails 
Ruby :: rails spreadsheet email attachment 
Ruby :: ruby timeout 
ADD CONTENT
Topic
Content
Source link
Name
2+1 =