ruby magic hash - LearnWithStella/rails_in_5 GitHub Wiki

Ruby magic arrays & hashes

Inspired by https://medium.com/@dallasbille/two-ways-of-finding-the-element-that-occurs-the-most-in-an-array-with-ruby-7fb484ea1a6d

Try it out in rails console

pencils = ['red', 'orange', 'purple', 'pink', 'yellow', 'purple', 'red', 'black', 'silver', 'white', 'purple']

colors = Hash.new(0)
pencils.each { |pencil| colors[pencil] +=1 }
colors
=> {"red"=>2, "orange"=>1, "purple"=>3, "pink"=>1, "yellow"=>1, "black"=>1, "silver"=>1, "white"=>1}

Oh but wait! They ain't ordered!

...too lazy to look for the color that occurs the most times!

colors.sort_by{ |color, count| count }
=> ["orange", 1], ["pink", 1], ["yellow", 1], ["black", 1], ["silver", 1], ["white", 1], ["red", 2], ["purple", 3](/LearnWithStella/rails_in_5/wiki/"orange",-1],-["pink",-1],-["yellow",-1],-["black",-1],-["silver",-1],-["white",-1],-["red",-2],-["purple",-3)

Shows the color that I have the most, and it also shows how many pencils of this color I have!

This will also give me the same information:

colors.max_by{ |color, count| count }
 => ["purple", 3]

… and more fun stuff

http://ruby.bastardsbook.com/chapters/enumerables/ https://www.slideshare.net/lehoang1417/ruby-syntax-blanknilempty