如果OpenStruct中不存在密钥,我该如何返回nil?(How can I return nil if a key does not exist in OpenStruct?)

编程入门 行业动态 更新时间:2024-10-11 11:21:02
如果OpenStruct中不存在密钥,我该如何返回nil?(How can I return nil if a key does not exist in OpenStruct?)

我有一个传递给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 #=> nil

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

更多推荐

本文发布于:2023-07-15 07:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1111417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   我该   中不   OpenStruct   exist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!