【问题标题】:Getting a NameError in very simple Ruby code [duplicate]在非常简单的 Ruby 代码中获取 NameError [重复]
【发布时间】:2015-09-02 04:58:01
【问题描述】:

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

pentagonals = []

def pent?(num)
  pentagonals.include?(num)
end

(1..1000).each {|i|
  pentagonals << (i * (3 * i - 1) / 2)
  }

puts pent?(1)

【问题讨论】:

    标签: ruby


    【解决方案1】:

    Ruby 中的全局变量通过初始 $ 与所有其他程序名称(如常规变量、类名称、方法名称、模块名称等)区分开来,因此您应该以这种方式更改程序:

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

    请注意,应谨慎使用全局变量,事实上它们很危险,因为它们可以从程序中的任何位置写入。

    【讨论】:

    • 我希望看到一个答案,解释什么是全局变量,为什么它们会解决这个问题,还有其他更好的解决方案。
    • 我会更新答案。
    • 我没有介绍不同类型的变量,但我习惯于将它们放入方法中并迭代它们,而不必指定它们是什么类型的变量。数组的处理方式是否不同(例如,它们是否默认分配了比字符串、布尔值等更本地化的变量层?)
    • 变量名与其类型无关。数组、字符串、布尔值等都是对象,从这方面来看都以相同的方式处理。改变的是它们的命名方式,以表示不同的范围或不同的用途。例如类属性名称以@开头,类和模块名称以大写字母开头,等等。
    • 好的,谢谢你的帮助!
    【解决方案2】:

    方法中的变量在方法范围内是本地的,除非它们作为参数传入。

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

    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? 
    

    【讨论】:

      猜你喜欢
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多