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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T20:30:49+00:00 2026-06-01T20:30:49+00:00

Possible Duplicate: Ruby: Nils in an IF statement Is there a clean way to

  • 0

Possible Duplicate:
Ruby: Nils in an IF statement
Is there a clean way to avoid calling a method on nil in a nested params hash?

Let’s say I try to access a hash like this:

my_hash['key1']['key2']['key3']

This is nice if key1, key2 and key3 exist in the hash(es), but what if, for example key1 doesn’t exist?

Then I would get NoMethodError: undefined method [] for nil:NilClass. And nobody likes that.

So far I deal with this doing a conditional like:

if my_hash['key1'] && my_hash['key1']['key2'] …

Is this appropriate, is there any other Rubiest way of doing so?

  • 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-01T20:30:50+00:00Added an answer on June 1, 2026 at 8:30 pm

    There are many approaches to this.

    If you use Ruby 2.3 or above, you can use dig

    my_hash.dig('key1', 'key2', 'key3')
    

    Plenty of folks stick to plain ruby and chain the && guard tests.

    You could use stdlib Hash#fetch too:

    my_hash.fetch('key1', {}).fetch('key2', {}).fetch('key3', nil)
    

    Some like chaining ActiveSupport’s #try method.

    my_hash.try(:[], 'key1').try(:[], 'key2').try(:[], 'key3')
    

    Others use andand

    myhash['key1'].andand['key2'].andand['key3']
    

    Some people think egocentric nils are a good idea (though someone might hunt you down and torture you if they found you do this).

    class NilClass
      def method_missing(*args); nil; end
    end
    
    my_hash['key1']['key2']['key3']
    

    You could use Enumerable#reduce (or alias inject).

    ['key1','key2','key3'].reduce(my_hash) {|m,k| m && m[k] }
    

    Or perhaps extend Hash or just your target hash object with a nested lookup method

    module NestedHashLookup
      def nest *keys
        keys.reduce(self) {|m,k| m && m[k] }
      end
    end
    
    my_hash.extend(NestedHashLookup)
    my_hash.nest 'key1', 'key2', 'key3'
    

    Oh, and how could we forget the maybe monad?

    Maybe.new(my_hash)['key1']['key2']['key3']
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Is there any wisdom behind “and”, “or” operators in Ruby ? What
Possible Duplicate: Transliteration in ruby I am searching for a simple way to convert
Possible Duplicate: Ruby: Any gems for threadpooling? Is there a better ruby lib thread
Possible Duplicate: Ruby Assignment Syntax I don't get the concept of an assignment method
Possible Duplicate: Sorting a hash in Ruby by its value first then its key.
Possible Duplicate: Which style of Ruby string quoting do you favour? Is there a
Possible Duplicate: Calling a Function From a String With the Function's Name in Ruby
Possible Duplicate: Changing a CSS rule-set from Javascript Dear experts, Is there a way
Possible Duplicate: Ruby: difference between || and ‘or’ Using Ruby || and or are
Possible Duplicate: ruby-debug with Ruby 1.9.3? I had heard rumors that ruby 1.9.3p125 has

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.