Created
December 3, 2014 21:28
-
-
Save uzzer/4c0b9f1e65a7f8aa4e18 to your computer and use it in GitHub Desktop.
Explanation for try ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
➜ ~ 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