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

  • Home
  • SEARCH
  • 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 900807
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T15:27:02+00:00 2026-05-15T15:27:02+00:00

In order to implement auto-vivification of Ruby hash, one can employ the following class

  • 0

In order to implement auto-vivification of Ruby hash, one can employ the following class

class AutoHash < Hash
  def initialize(*args)
    super()
    @update, @update_index = args[0][:update], args[0][:update_key] unless 
args.empty?
  end

  def [](k)
    if self.has_key?k
      super(k)
    else
      AutoHash.new(:update => self, :update_key => k)
    end
  end

  def []=(k, v)
    @update[@update_index] = self if @update and @update_index
    super
  end

  def few(n=0)
    Array.new(n) { AutoHash.new }
  end
end

This class allows to do the following things

a = AutoHash.new
a[:a][:b] = 1
p a[:c] # => {}             # key :c has not been created
p a     # => {:a=>{:b=>1}}  # note, that it does not have key :c

a,b,c = AutoHash.new.few 3
b[:d] = 1
p [a,b,c] # => [{}, {:d=>1}, {}]  # hashes are independent

There is a bit more advanced definition of this class proposed by Joshua, which is a bit hard for me to understand.

Problem

There is one situation, where I think the new class can be improved. The following code fails with the error message NoMethodError: undefined method '+' for {}:AutoHash

a = AutoHash.new
5.times { a[:sum] += 10 }

What would you do to handle it? Can one define []+= operator?


Related questions

  1. Is auto-initialization of multi-dimensional hash array possible in Ruby, as it is in PHP?
  2. Multiple initialization of auto-vivifying hashes using a new operator in Ruby
    ruby hash initialization r
  3. still open: How to create an operator for deep copy/cloning of objects in Ruby?
  • 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-05-15T15:27:03+00:00Added an answer on May 15, 2026 at 3:27 pm

    There is no way to define a []+= method in ruby. What happens when you type

    x[y] += z
    

    is

    x[y] = x[y] + z
    

    so both the [] and []= methods are called on x (and + is called on x[y], which in this case is an AutoHash). I think that the best way to handle this problem would be to define a + method on AutoHash, which will just return it’s argument. This will make AutoHash.new[:x] += y work for just about any type of y, because the “empty” version of y.class ('' for strings, 0 for numbers, …) plus y will almost always equal y.

    class AutoHash
      def +(x); x; end
    end
    

    Adding that method will make both of these work:

    # Numbers:
    a = AutoHash.new
    5.times { a[:sum] += 10 }
    a[:sum] #=> 50
    
    # Strings:
    a = AutoHash.new
    5.times { a[:sum] += 'a string ' }
    a[:sum] #=> "a string a string a string a string a string "
    

    And by the way, here is a cleaner version of your code:

    class AutoHash < Hash
      def initialize(args={})
        super
        @update, @update_index = args[:update], args[:update_key]
      end
    
      def [](k)
        if has_key? k
          super(k)
        else
          AutoHash.new :update => self, :update_key => k
        end
      end
    
      def []=(k, v)
        @update[@update_index] = self if @update and @update_index
        super
      end
    
      def +(x); x; end
    
      def self.few(n)
        Array.new(n) { AutoHash.new }
      end
    end
    

    🙂

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

Sidebar

Related Questions

How do i implement a java comparator class which can sort the order of
I wanted to implement a default sort order in my domain class and immediately
I was wondering how exactly does TCP implement in-order delivery. lets say this is
I need to implement a plugin architecture within c#/.net in order to load custom
I'm trying to implement a custom SimpleCursorAdapter in order to switch out layouts in
I'm looking to implement a warning if the user attempts to leave the order
My requirement is to implement auto complete in my text box with my rails
I am trying to implement face recognition on camera captured faces.In order to make
I want my client class to run a thread that sends String information (order)
Take a look at the following classes (UNIdirectional @OneToMany) @Entity public class Team {

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.