Search code examples
rubynomethoderror

How can I return nil if a key does not exist in OpenStruct?


I have a hash that passed to OpenStruct in order to make it word with a .. This works perfectly. But when ever I try to access a key that does not exist undefined method <unknown key> for #<Hash:0x7f24ea884210> (NoMethodError) is raised. How can I make it return nil?

If I try the same thing with the original hash I get nil but not with OpenStruct!!

The snippet from the program:

TXT_HASH = load_data("test.txt")
pp TXT_HASH[:ftp][:lastname]  ## print nil as lastname does not exist

TXT = OpenStruct.new(TXT_HASH)
pp TXT.ftp.lastname  ## raises NoMethodError ## Can it return nil?

Solution

  • OpenStruct is not recursive. In this case TXT.ftp returns a Hash, not an OpenStruct, so #lastname is not defined.

    If you want, there is a library called recursive-open-struct. Use it like this:

    require 'recursive-open-struct'
    
    TXT = RecursiveOpenStruct.new(TXT_HASH)
    pp TXT.ftp.lastname #=> nil