我有一个传递给OpenStruct的哈希,以便用a表示. 。 这非常有效。 但是当我尝试访问不存在的键时,会引发undefined method <unknown key> for #<Hash:0x7f24ea884210> (NoMethodError) 。 怎么能让它返回nil ?
如果我用原始哈希尝试相同的东西,我会得到nil但不是与OpenStruct !
该程序的片段:
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?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?最满意答案
OpenStruct不是递归的。 在这种情况下, TXT.ftp返回Hash,而不是OpenStruct,因此#lastname 。
如果需要,有一个名为recursive-open-struct的库。 像这样用它:
require 'recursive-open-struct' TXT = RecursiveOpenStruct.new(TXT_HASH) pp TXT.ftp.lastname #=> nilOpenStruct 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更多推荐
发布评论