From: Dave Aronson Date: 2011-09-16T07:33:30+09:00 Subject: Re: Some newbie questions On Thu, Sep 15, 2011 at 15:46, Vladimir Van Bauenhoffer wrote: > 1. What does @ mean in Ruby? Im sure I have seen variables like this: > @variable. A new datatype like the :symbol perhaps? Someone beat me to this one, so I'll just preemptively add, @@ means it's a class variable. > 2. Hash.new {0} >   anotherhash.values.each {|x| thecreatedhash[x] += 1} > > What makes the hash created above different from a hash created the > normal way? I can execute the block on a hash created with that method > but not a normal empty hash created manually. You've already clarified that "normal" means {}. But what I don't get is how you're using it. Do you mean that: thecreatedhash = Hash.new {0} anotherhash.values.each {|x| thecreatedhash[x] += 1} yields different results from: thecreatedhash = {} anotherhash.values.each {|x| thecreatedhash[x] += 1} ? That boils down to the difference between "Hash.new {0}" and "{}". The latter will return an empty hash such that uninitialized slots have a nil value, as usual. The former is a good bit more complicated. There is documentation at: http://www.ruby-doc.org/core/classes/Hash.html#M000718 At first glance the docs would lead me to believe that the uninitialized slots should return the value {0}, using the Hash.new(object) syntax, but the braces in fact make it take that as a code block, even though it's not using the args, so it's using the third syntax (Hash.new {|hash, key| block }). This means it returns 0, the result of that code block, for all uninitialized slots. Occasional confusion between hashes and code blocks is one of the subtleties of Ruby. So, in the former case, anotherhash would cause corresponding slots of thecreatedhash to be set to 1, because they start at 0 and get incremented. In the latter, they'd start as nil, and you can't add 1 to that, so you'd get a NoMethodError. Is ths the behavior you're seeing? -Dave -- LOOKING FOR WORK, preferably Ruby on Rails, in NoVa/DC; see main web site. Main Web Site: davearonson.com Programming Blog: codosaur.us Excellence Blog: dare2xl.com