# START COPY AND PASTE HERE # Ruby Hash Sorting Tutorial # initialize hash using following syntax: hashName = { } # initialize hash items using hash-rocket => syntax # example: food1 => chlorella # food1 is a key, chlorella is a value # a hash can have multiple values for one key superfoods = { "food1" => "chlorella", # Add items with => syntax "food2" => "nori", "food3" => "bee pollen", "food4" => "sauerkraut", "food5" => "kimchi" } puts # code readability puts "SUPERFOODS HASH food3 IS:" # print title puts superfoods["food3"]; # print food3 puts "ALL SUPERFOODS KEYS" # print title puts superfoods.keys # print all hash keys puts "ALL SUPERFOODS VALUES" puts superfoods.values # print all hash values puts # prints empty line for code readability puts # SYNTAX DETAILS # ======================= # Hash sorting syntax: hashName.sort{| range | sortOrder }.each {| element | puts } # range = rows of keys and values in data set # range has arbitrary letters for data, a for keys, b for values, so | a, b | # sortOrder = process which items (columns) in the list? # sortOrder. In this case a[0] is the first item in Keys, the first data set # .each is a Ruby method to COUNT - LOOP through data items until done puts puts "SORTING CODE STARTS HERE" puts "=======================" puts puts "KEYS COLUMN FIRST in ALPHA ORDER" # Hash sorting syntax: hashName.sort{| range | sortOrder }.each {| element | puts } # a = keys column, b = values column # a <=> b is alpha or reverse-alpha # a[0] or a[1] specifies column order # {elem[0]} : {elem[1]} displays keys column first superfoods.sort{|a,b| a[0]<=>b[0]}.each { |elem| puts "#{elem[0]}: #{elem[1]}" # keys first } puts puts "KEYS COLUMN FIRST in REVERSE ALPHA" superfoods.sort{|a,b| b[0]<=>a[0]}.each { |elem| puts "#{elem[0]}: #{elem[1]}" # keys first } puts puts "VALUES COLUMN FIRST in ALPHA ORDER" superfoods.sort{|a,b| a[1]<=>b[1]}.each { |elem| puts "#{elem[1]}: #{elem[0]}" # values first } puts puts "VALUES COLUMN FIRST in REVERSE ALPHA" superfoods.sort{|a,b| b[1]<=>a[1]}.each { |elem| puts "#{elem[1]}: #{elem[0]}" # values first } puts puts "VALUES COLUMN FIRST in REVERSE ALPHA, COUNTER VARS TO J,K" # instead of |a,b| counters vars changed to |j,k| just to demonstrate they are arbitrary # | j,k | is range, j[ ] and k[ ] are counters-identifiers superfoods.sort{|j,k| k[1]<=>j[1]}.each { |elem| puts "#{elem[1]}: #{elem[0]}" # values first } puts # end ruby hash sorting tutorial # END COPY AND PASTE HERE