【问题标题】:Assistance with ruby def帮助 ruby​​ def
【发布时间】:2013-09-18 23:43:59
【问题描述】:

所以,我是 ruby​​ 的新手,对它非常好奇。我来自python。在 python 中,我会这样做以查看字典中是否存在某些内容。

dictionary = dict()
dictionary['key'] = 5
def inDictionary(key):
    if key in dictionary:
       execute code
    else:
        other code

对我来说相当简单,另一方面,在 ruby​​ 中我该怎么做?我一直在尝试类似的东西

dictionary = Hash.new
dictionary['key'] = 5
def isDictionary(key)
    if dictionary.has_key?(key)
       puts 'has key'
    end
end

我收到错误,isDictionary 未定义局部变量或方法“字典”。我做错了什么,提前谢谢。

【问题讨论】:

  • 那是因为当您在 isDictionary 方法中调用字典时,字典的范围发生了变化。我建议在其中创建一个类字典和一个 isDictionary 方法,以便您通过该类生成的所有实例都可以使用 isDictionary。希望这是有道理的

标签: python ruby


【解决方案1】:

在 Ruby 中,defclassmodule 关键字启动新的本地范围。这意味着 dictionary 变量(定义为本地变量)在此 isDictionary 函数中不可访问,因为最新版本有其自己的范围。

当然,您可以使用$ sigil 标记您的变量以使其成为全局变量,但您最好不要这样做。 Ruby 的全部意义在于使对象——数据的集合和处理/转换该数据的方法——尽可能地“与生俱来”。

在这种情况下,最自然的解决方案是定义类 Dictionary,将字典作为其实例变量(使用@ sigil),然后在类方法 isDictionary 中访问此变量。

【讨论】:

    【解决方案2】:

    试试这个

    @dictionar­y = Hash.­new
    @dictionar­y['key'] = 5
    def isDic­tionary(ke­y)
        if @dict­ionary.has­_key?(key)­
           puts 'has key'
        end
    end
    
    isDictionary("key")
    

    我所做的是通过将dictionary 变量转换为实例变量@dictionary 来增强它的范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 2011-04-17
      • 1970-01-01
      相关资源
      最近更新 更多