【问题标题】:Ruby testing for definition of a variable用于定义变量的 Ruby 测试
【发布时间】:2011-12-18 23:42:38
【问题描述】:

我知道还有其他类似的问题,例如:

  1. Ruby: how to check if variable exists within a hash definition
  2. Checking if a variable is defined?

但答案并不完全令人满意。

我有:

ruby-1.9.2-p290 :001 > a=Hash.new
 => {} 
ruby-1.9.2-p290 :002 > a['one']="hello"
 => "hello"
ruby-1.9.2-p290 :006 > defined?(a['one']['some']).nil?
 => false 
ruby-1.9.2-p290 :007 > a['one']['some'].nil?
 => true

好像是这样的:

if a['one']['some'].nil?
  a['one']['some']=Array.new
end 

就足够了。它是否正确?这对任何数据类型都正确吗?被定义为?这种情况下需要吗?

谢谢

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您似乎混淆了两个概念。一种是定义了变量,另一种是定义了哈希键。由于哈希在某些时候是一个变量,因此必须对其进行定义。

    defined?(a)
    # => nil
    
    a = { }
    # => {}
    
    defined?(a)
    # => "local-variable"
    
    a.key?('one')
    # => false
    
    a['one'] = 'hello'
    # => 'hello'
    
    a.key?('one')
    # => true
    

    某个东西可以同时是键和nil,这是有效的。哈希没有定义或未定义的概念。关键在于密钥是否存在。

    使用.nil? 进行测试的唯一原因是区分两个可能的非真实值:nilfalse。如果您永远不会在这种情况下使用false,那么调用.nil? 就不必要地冗长。换句话说,if (x.nil?) 等同于 if (x),前提是 x 永远不会是字面上的 false

    您可能想要使用||= 模式,如果现有值是nilfalse,它将分配一些东西:

    # Assign an array to this Hash key if nothing is stored there
    a['one']['hello'] ||= [ ]
    

    更新:根据Bruce的评论编辑。

    【讨论】:

    • 技术上“定义?”返回一个字符串或 nil,而不是 true/false。
    • 感谢详细回答-更有意义;将需要使用不同的处理方式
    • @Bruce 你是对的,我没有意识到。答案已相应更新。
    【解决方案2】:

    我不得不在 Google 中深入挖掘许多页面,但最终我从 Ruby 1.9 规范中找到了this useful bit

    “在所有情况下,测试 [已定义?] 都是在不评估操作数的情况下进行的。”

    所以发生的事情是它看起来:

    a['one']['some']
    

    并说“正在向‘a’对象发送‘operator []’消息——这是一个方法调用!”和定义的结果?那就是“方法”。

    那么当你检查 nil? 时,字符串“method”显然不是 nil。

    【讨论】:

      【解决方案3】:

      除了@tadmans 的回答之外,您在示例中实际所做的是检查字符串"some" 是否包含在字符串"hello" 中,该字符串存储在您的哈希值"one" 的位置。

      a = {}
      a['one'] = 'hello'
      a['one']['some'] # searches the string "some" in the hash at key "one"
      

      一个更简单的例子:

      b = 'hello'
      b['he'] # => 'he'
      b['ha'] # => nil
      

      这就是为什么defined? 方法没有像您预期的那样返回nil,而是返回"method"

      【讨论】:

      • 一个合理的想法,但事实证明这是定义的?不计算它的参数,所以它永远不会费心去弄清楚 a['one'] 的计算结果是“hello”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2020-11-04
      • 2013-04-18
      • 2012-11-16
      • 2016-08-10
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多