Google Groups Home
Help | Sign in
Message from discussion assigning to hash keys when there is a default value?
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
dbl...@wobblini.net  
View profile
 More options Sep 3 2007, 7:37 am
Newsgroups: comp.lang.ruby
From: dbl...@wobblini.net
Date: Mon, 3 Sep 2007 20:37:13 +0900
Local: Mon, Sep 3 2007 7:37 am
Subject: Re: assigning to hash keys when there is a default value?

[ multipart_mixed_part < 1K ]
  This message is in MIME format.  The first part should be readable text,
  while the remaining parts are likely unreadable without MIME-aware tools.

Hi --

On Mon, 3 Sep 2007, 7stud -- wrote:
> Peña, Botp wrote:
>> they should be different (note, that has nothing to do w the bug dBlack
>> is pointing at) and the output should be,

>> 5
>> {2=>5}    #<---dblack is complaining here because the ruby output is {}

>> nil
>> {2=>10}

> Yes.  That is what I am complaining about too!  Your are right: the
> second line for each section of the output should be different--I
> mispoke.  What I want to know is why the the output is {} and not
> {2=>5}.

> The author of "The Ruby Way (2nd ed)" presents the two examples as well
> as the different output for each example, yet he doesn't explain the
> reason for the different output.  He suggests that you can use ||= to
> selectively assign values only to keys that don't exist.  The point I
> think he was trying to make with the two examples is that when you have
> a default value for non-existent keys, all keys "exist", so ||= will not
> create new keys with the default value.

I don't have the book at hand but the default value definitely doesn't
mean that all keys exist (or even "exist" :-)

irb(main):003:0> h = Hash.new(5)
=> {}
irb(main):004:0> h[1]
=> 5
irb(main):005:0> h.has_key?(1)
=> false

The only possible explanation I can come up with, which I don't like,
is that:

   h[2] ||= 10

is being treated like:

   5 = 5 || 10

which is just another can of worms.

David

--
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2008 Google