Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8839649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T10:17:00+00:00 2026-06-14T10:17:00+00:00

Possible Duplicate: Ruby method Array#<< not updating the array in hash Strange ruby behavior

  • 0

Possible Duplicate:
Ruby method Array#<< not updating the array in hash
Strange ruby behavior when using Hash.new([])

I’ve been doing Koans which is great, and as I go along I find no major trouble, but I stumbled upon this, and can’t make any sense out of it:

    def test_default_value_is_the_same_object
        hash = Hash.new([])

        hash[:one] << "uno"
        hash[:two] << "dos"

        assert_equal ["uno", "dos"], hash[:one]   # But I only put "uno" for this key!
        assert_equal ["uno", "dos"], hash[:two]   # But I only put "dos" for this key!
        assert_equal ["uno", "dos"], hash[:three] # I didn't shove anything for :three!

        assert_equal true, hash[:one].object_id == hash[:two].object_id 
    end

All the tests are passing (I just looked at the error which helped me guess the right assertions to write).

The last assert, ok, they both were not initialized so their values have got to have the same object ID since they both take the default.

I don’t understand why the default value was altered, I’m not even entirely sure that’s what happened.

I tried it out in IRB, thinking maybe some tampering on Hash/Array was done to make me crazy, but I get the same result.

I first thought hash[:one] << "uno" would imply hash to become { one: ["uno] }, but it remains { }.
Although I’m guessing << only calls push, and new keys are only added when you use the = sign

Please tell me what I missed.

EDIT: I’m using Ruby 1.9.3

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T10:17:01+00:00Added an answer on June 14, 2026 at 10:17 am

    When you use the default argument for a Hash, the same object is used for all keys that have not been explicitly set. This means that only one array is being used here, the one you passed into Hash.new. See below for evidence of that.

    >> h = Hash.new([])
    => {}
    >> h[:foo] << :bar
    => [:bar]
    >> h[:bar] << :baz
    => [:bar, :baz]
    >> h[:foo].object_id
    => 2177177000
    >> h[:bar].object_id
    => 2177177000
    

    The weird thing is that as you found, if you inspect the hash, you’ll find that it is empty! This is because only the default object has been modified, no keys have yet been assigned.

    Fortunately, there is another way to do default values for hashes. You can provide a default block instead:

    >> h = Hash.new { |h,k| h[k] = [] }
    => {}
    >> h[:foo] << :bar
    => [:bar]
    >> h[:bar] << :baz
    => [:baz]
    >> h[:foo].object_id
    => 2176949560
    >> h[:bar].object_id
    => 2176921940
    

    When you use this approach, the block gets executed every time an unassigned key is used, and it is provided the hash itself and the key as an argument. By assigning the default value within the block, you can be sure that a new object will get created for each distinct key, and that the assignment will happen automatically. This is the idiomatic way of creating a “Hash of Arrays” in Ruby, and is generally safer to use than the default argument approach.

    That said, if you’re working with immutable values (like numbers), doing something like Hash.new(0) is safe, as you’ll only change those values by re-assignment. But because I prefer to keep fewer concepts in my head, I pretty much use the block form exclusively.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Ruby Hash with Duplicate Keys? I defined a hash: sorted_words = Hash.new(0)
Possible Duplicate: check if value exists in array in Ruby I have this method
Possible Duplicate: How to turn a string into a method call? Using Ruby 1.9,
Possible Duplicate: Using 'return' in a Ruby block I'm new to Ruby, and was
Possible Duplicate: What Ruby IDE do you prefer? I've generally been doing stuff on
Possible Duplicate: Ruby syntax question: Rational(a, b) and Rational.new!(a, b) I'm in the process
Possible Duplicate: Ruby: difference between || and ‘or’ Using Ruby || and or are
Possible Duplicate: Array slicing in Ruby: looking for explanation for illogical behaviour (taken from
Possible Duplicate: Ruby Assignment Syntax I don't get the concept of an assignment method
Possible Duplicate: Checking if a variable is defined in Ruby using Tilt's template render

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.