Skip to content

Instantly share code, notes, and snippets.

@uzzer
Created December 3, 2014 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uzzer/4c0b9f1e65a7f8aa4e18 to your computer and use it in GitHub Desktop.
Save uzzer/4c0b9f1e65a7f8aa4e18 to your computer and use it in GitHub Desktop.
Explanation for try ruby
➜ ~ irb
:001 > books = {}
:002 > books[:one] = :good
:003 > books[:two] = :bad
:004 > books[:three] = :good
=> :good
:012 > books
=> {:one=>:good, :two=>:bad, :three=>:good}
:005 > ratings = Hash.new(0) # Here is important magic! Default value for hash is zero, usually it is nil
=> {}
:006 > ratings[:any] # let's try random call for hash
=> 0 # It returns default value 0
:007 > # Let's check step by step "books.values.each {|rate| ratings[rate] += 1}"
:008 > books.values
=> [:good, :bad, :good]
.each{|rate| action }
means iterate through iteratable and store value in variable rate
block will be caleld 3 times, values of rate inside block will be [:good, :bad, :good]
# first time rate equals :good
:009 > ratings[:good] # let's check default value of ratings[:good]
=> 0 # it's zero because of special Hash
# a +=1 is the same like a = a + 1
:010 > ratings[:good] = ratings[:good] + 1
# is equals to ratings[:good] = 0 + 1
=> 1
:011 > ratings[:good] # is now equals 1
# let's run and see the result
:014 > books.values.each { |rate| ratings[rate] += 1 }
=> [:good, :bad, :good] # return books.values, but made some action on ratings[rate]
:015 > ratings # now collects count of different hash values
=> {:good=>2, :bad=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment