From: Robert Klemme Date: 2006-11-26T05:50:07+09:00 Subject: Re: coding practise On 25.11.2006 11:59, Paul Lutus wrote: > sempsteen wrote: > >> Hi all, >> First of all sorry for my english. >> I'm a Ruby newbie, trying to learn the language from the book, "The >> Pragmatic Programmer's Guide". I loved the language very much. Now i >> have some question marks about some issues. >> If you help me understand this concept i'll be very happy. >> >> 1-) What does "Hash#has_key?" actually do? > > It returns true if provided with a key that is present in the hash. > >> Why do we need such a method in spite of using the result of "Hash#[]" >> method which will return nil for a non-present key. As others have pointed out if Hash#[] returns nil you do not know whether the key was in the hash with nil associated or whether it was missing. irb(main):001:0> h={} => {} irb(main):002:0> h.has_key? :foo => false irb(main):003:0> h[:foo] = nil => nil irb(main):004:0> h[:foo] => nil irb(main):005:0> h.has_key? :foo => true irb(main):006:0> h.size => 1 irb(main):007:0> h => {:foo=>nil} However, in practice this is often negligible since you rarely use nil as a value in a Hash. > The method has_key? is faster than using the key to find and return a value, > which is what Hash#[] must do. This is wrong: a hash lookup has to be done for both. Kind regards robert