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 8897223
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T00:17:01+00:00 2026-06-15T00:17:01+00:00

I need to populate a Hash with various values. Some of values are accessed

  • 0

I need to populate a Hash with various values. Some of values are accessed often enough and another ones really seldom.

The issue is, I’m using some computation to get values and populating the Hash becomes really slow with multiple keys.

Using some sort of cache is not a option in my case.

I wonder how to make the Hash compute the value only when the key is firstly accessed and not when it is added?

This way, seldom used values wont slow down the filling process.

I’m looking for something that is “kinda async” or lazy access.

  • 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-15T00:17:03+00:00Added an answer on June 15, 2026 at 12:17 am

    There are many different ways to approach this. I recommend using an instance of a class that you define instead of a Hash. For example, instead of…

    # Example of slow code using regular Hash.
    h = Hash.new
    h[:foo] = some_long_computation
    h[:bar] = another_long_computation
    # Access value.
    puts h[:foo]
    

    … make your own class and define methods, like this…

    class Config
      def foo
        some_long_computation
      end
    
      def bar
        another_long_computation
      end
    end
    
    config = Config.new
    puts config.foo
    

    If you want a simple way to cache the long computations or it absolutely must be a Hash, not your own class, you can now wrap the Config instance with a Hash.

    config = Config.new
    h = Hash.new {|h,k| h[k] = config.send(k) }
    # Access foo.
    puts h[:foo]
    puts h[:foo]  # Not computed again. Cached from previous access.
    

    One issue with the above example is that h.keys will not include :bar because you haven’t accessed it yet. So you couldn’t, for example, iterate over all the keys or entries in h because they don’t exist until they’re actually accessed. Another potential issue is that your keys need to be valid Ruby identifiers, so arbitrary String keys with spaces won’t work when defining them on Config.

    If this matters to you, there are different ways to handle it. One way you can do it is to populate your hash with thunks and force the thunks when accessed.

    class HashWithThunkValues < Hash
      def [](key)
        val = super
        if val.respond_to?(:call)
          # Force the thunk to get actual value.
          val = val.call
          # Cache the actual value so we never run long computation again.
          self[key] = val
        end
    
        val
      end
    end
    
    h = HashWithThunkValues.new
    # Populate hash.
    h[:foo] = ->{ some_long_computation }
    h[:bar] = ->{ another_long_computation }
    h["invalid Ruby name"] = ->{ a_third_computation }  # Some key that's an invalid ruby identifier.
    # Access hash.
    puts h[:foo]
    puts h[:foo]  # Not computed again. Cached from previous access.
    puts h.keys  #=> [:foo, :bar, "invalid Ruby name"]
    

    One caveat with this last example is that it won’t work if your values are callable because it can’t tell the difference between a thunk that needs to be forced and a value.

    Again, there are ways to handle this. One way to do it would be to store a flag that marks whether a value has been evaluated. But this would require extra memory for every entry. A better way would be to define a new class to mark that a Hash value is an unevaluated thunk.

    class Unevaluated < Proc
    end
    
    class HashWithThunkValues < Hash
      def [](key)
        val = super
    
        # Only call if it's unevaluated.
        if val.is_a?(Unevaluated)
          # Force the thunk to get actual value.
          val = val.call
          # Cache the actual value so we never run long computation again.
          self[key] = val
        end
    
        val
      end
    end
    
    # Now you must populate like so.
    h = HashWithThunkValues.new
    h[:foo] = Unevaluated.new { some_long_computation }
    h[:bar] = Unevaluated.new { another_long_computation }
    h["invalid Ruby name"] = Unevaluated.new { a_third_computation }  # Some key that's an invalid ruby identifier.
    h[:some_proc] = Unevaluated.new { Proc.new {|x| x + 2 } }
    

    The downside of this is that now you have to remember to use Unevaluted.new when populating your Hash. If you want all values to be lazy, you could override []= also. I don’t think it would actually save much typing because you’d still need to use Proc.new, proc, lambda, or ->{} to create the block in the first place. But it might be worthwhile. If you did, it might look something like this.

    class HashWithThunkValues < Hash
      def []=(key, val)
        super(key, val.respond_to?(:call) ? Unevaluated.new(&val) : val)
      end
    end
    

    So here is the full code.

    class HashWithThunkValues < Hash
    
      # This can be scoped inside now since it's not used publicly.
      class Unevaluated < Proc
      end
    
      def [](key)
        val = super
    
        # Only call if it's unevaluated.
        if val.is_a?(Unevaluated)
          # Force the thunk to get actual value.
          val = val.call
          # Cache the actual value so we never run long computation again.
          self[key] = val
        end
    
        val
      end
    
      def []=(key, val)
        super(key, val.respond_to?(:call) ? Unevaluated.new(&val) : val)
      end
    
    end
    
    h = HashWithThunkValues.new
    # Populate.
    h[:foo] = ->{ some_long_computation }
    h[:bar] = ->{ another_long_computation }
    h["invalid Ruby name"] = ->{ a_third_computation }  # Some key that's an invalid ruby identifier.
    h[:some_proc] = ->{ Proc.new {|x| x + 2 } }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to populate a MySQL table with random SHA-1 hash values, generated by
Hi i need to populate a combobox using the selected value in another combo.
I need to populate a table using a programmatically populated ArrayList, and my requirement
I need to populate the data which is in the database fields using nHibernate
I need to know how to populate a Label with values from Store .
I am using LINQ-to-Entities and need to populate a ListView using a select statement
I need populate with dummy values a table. I need create a random generated
I need to populate a JAX Bean from XML, however there is no setter
I need to populate a dropdownlist in ruby on rails with the data in
I need to populate a .net DataGridView from a collection physically (without data binding)

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.