K
Kaye Ng
Hello. First of all, I'm reading this ebook,
http://www.ruby-doc.org/docs/ProgrammingRuby/
is it a good book?
---------------------------------------------------------------------------------
instSection['oboe'] » "woodwind"
instSection['cello'] » "string"
instSection['bassoon'] » nil
As the last example shows, a hash by default returns nil when indexed by
a key it doesn't contain. Normally this is convenient, as nil means
false when used in conditional expressions. Sometimes you'll want to
change this default. For example, if you're using a hash to count the
number of times each key occurs, it's convenient to have the default
value be zero. This is easily done by specifying a default value when
you create a new, empty hash.
histogram = Hash.new(0)
histogram['key1'] » 0
histogram['key1'] = histogram['key1'] + 1
histogram['key1'] » 1
-------------------------------------------------------------------
I don't understand the histogram example (starting from "For example, if
you're using a hash to count the...") What does Hash.new(0) do and what
is it used for?
A practical and simple example would be great. Thank you Ruby experts!
http://www.ruby-doc.org/docs/ProgrammingRuby/
is it a good book?
---------------------------------------------------------------------------------
instSection['oboe'] » "woodwind"
instSection['cello'] » "string"
instSection['bassoon'] » nil
As the last example shows, a hash by default returns nil when indexed by
a key it doesn't contain. Normally this is convenient, as nil means
false when used in conditional expressions. Sometimes you'll want to
change this default. For example, if you're using a hash to count the
number of times each key occurs, it's convenient to have the default
value be zero. This is easily done by specifying a default value when
you create a new, empty hash.
histogram = Hash.new(0)
histogram['key1'] » 0
histogram['key1'] = histogram['key1'] + 1
histogram['key1'] » 1
-------------------------------------------------------------------
I don't understand the histogram example (starting from "For example, if
you're using a hash to count the...") What does Hash.new(0) do and what
is it used for?
A practical and simple example would be great. Thank you Ruby experts!