协助ruby def

ana*_*kin 1 ruby python

所以,我是红宝石的新手并且非常好奇.我是从python出来的.在python中,我会这样做,看看字典中是否存在某些内容.

dictionary = dict()
dictionary['key'] = 5
def inDictionary(key):
    if key in dictionary:
       execute code
    else:
        other code
Run Code Online (Sandbox Code Playgroud)

对我来说相当简单,另一方面,在红宝石中我该怎么做?我一直在尝试像

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

我得到错误,isDictionary未定义局部变量或方法"字典".我做错了什么,并提前感谢.

rai*_*7ow 5

在Ruby中,def,class,和module关键字开始新的局部范围.这意味着dictionary在此isDictionary函数中无法访问变量(定义为本地),因为最新版本具有自己的范围.

当然,您可以使用$sigil 标记变量以使其变为全局变量,但您最好不要这样做.Ruby的重点在于制作对象 - 数据集合和处理/转换数据的方法 - 尽可能"天生".

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