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 2 2007, 10:19 pm
Newsgroups: comp.lang.ruby
From: dbl...@wobblini.net
Date: Mon, 3 Sep 2007 11:19:09 +0900
Local: Sun, Sep 2 2007 10:19 pm
Subject: Re: assigning to hash keys when there is a default value?
Hi --

On Mon, 3 Sep 2007, 7stud -- wrote:
> Can someone explain why there is a difference in the second line of
> output for the two hashes:

> h = Hash.new(5)

> puts h[2]

> h[2] ||= 10
> p h

> #----------
> puts
> #----------

> h = Hash.new

> puts h[2]

> h[2] ||= 10
> p h

> ---output:--
> 5
> {}

> nil
> {2=>10}

x ||= y is, I think, always supposed to be exactly equivalent to
x = x || y, so that line in your first hash should be equivalent to:

   h[2] = 5 || 10

which should assign 5 to h[2]. It looks to me like you've found a bug.
I can't think of any reason (and I really hope there isn't one,
because having an exception to that ||= rule would be very messy) why
using a default hash value would make any difference here. It's still
5 || 10 on the rhs, and it's still just an assignment.

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