2012-03-18 38 views
0

时不能设置变量相同的名称,方法名考虑下面的代码ruby​​ koan? - 映射

def salt 
    [] 
end 

def pepper 
    salt = salt.map{ |grain| 'ok' } 
end 

给出以下结果:

NoMethodError (undefined method `map' for nil:NilClass): 

为什么这些情况正是导致错误?这是意想不到的。

回答

5

因为您的本地变量saltshadowing方法salt。由于刚刚定义了变量salt,因此其值为nil。您可以通过在实例上明确调用salt来解决此问题,以获取该方法:

def pepper 
    salt = self.salt.map{ |grain| 'ok' } 
end 
+0

有趣。他们这样做,似乎很奇怪,而不是计算后设置。但它适用于其他情况,例如定义无效变量或例如:'a,b = [x]',所以a == x和b == nil – 2012-03-18 05:20:10

+1

@PeterEhrlich只要您执行了'foo ='' ,将定义'foo'。这意味着像'foo = foo'这样的结果'foo'是'nil'而不是'NameError'。 – 2012-03-18 05:24:28