在非常简单的Ruby代码中获取NameError



我得到一个NameError,这可能表明我的数组"pentagonals"是未定义的。但如果我没有在第一行定义它,我就是猴子的叔叔。我忘记/误解了什么?目标是编写一个方法,告诉我给定的数字是否为五边形。

pentagonals = []
def pent?(num)
  pentagonals.include?(num)
end
(1..1000).each {|i|
  pentagonals << (i * (3 * i - 1) / 2)
  }
puts pent?(1)

Ruby中的全局变量与其他所有程序名(如常规变量,类名,方法名,模块名等)通过初始化的$来区分,所以你应该这样修改你的程序:

$pentagonals = []
def pent?(num)
  $pentagonals.include?(num)
end
(1..1000).each {|i|
  $pentagonals << (i * (3 * i - 1) / 2)
  }
puts pent?(1)

请注意,全局变量应该谨慎使用,实际上它们是危险的,因为它们可以从程序中的任何地方写入。

方法中的变量是方法作用域的局部变量,除非它们作为参数传入。

该方法还可以访问同一作用域中的全局变量、类变量和其他方法。

class MyClass
  # calling methods in the same class
  def method1
    method2
  end 
  def method2
    puts 'method2 was called'
  end
  # getter / setter method pair for class variables
  # @class_variable is only accessible within this class
  def print_class_variable
    puts @class_variable
  end
  def set_class_variable(param)
    @class_variable = param
  end
  # global variables can be accessed from anywhere
  def print_global_var 
    puts $global_variable 
  end
  def self.some_class_method
    # cannot be directly accessed by the instance methods above 
  end
end

请注意,不建议使用全局变量,因为它们很容易导致冲突和歧义。

class Dog
  $name = "Dog" 
end
class Cat
  $name = "Cat"
end
puts $name
# which one does $name refer to? 

最新更新