Ruby使用属性数组调用attr方法

Ruby使用属性数组调用attr方法,ruby,Ruby,请解释我为什么要在attr之前定义attr\u列表?我不明白我为什么要那样做 class Question def self.attr_list [:id, :name] end attr *self.attr_list end 与def不同,在点击return以运行程序后,会立即逐行执行类: class Dog x = 10 puts x end --output:-- 10 您调用了self.attr_list(),但是def位于该行之后,因此该方法

请解释我为什么要在
attr
之前定义
attr\u列表
?我不明白我为什么要那样做

class Question
  def self.attr_list
    [:id, :name]
  end

  attr *self.attr_list
end


与def不同,在点击return以运行程序后,会立即逐行执行类:

class Dog
  x = 10
  puts x
end

--output:--
10

您调用了self.attr_list(),但是def位于该行之后,因此该方法还不存在

使用def,您可以编写以下内容:

def do_math()
  10/0
end
在调用该方法之前,不会出现错误

但是,当您创建一个类的实例时,该类中的所有代码都已经执行,创建了在该类中定义的方法和常量


顺便说一下,您永远不需要使用
attr
,因为ruby 1.8.7+有
attr\u访问器(读写器),
attr\u读写器
,和
attr\u写写器
,这是一个很好的答案。另外,不要忘记Ruby是一种OO脚本语言。如果您来自更结构化的语言,如C或Java,您可能希望代码以
main
函数开头;然而,在Ruby中,文件是在加载时执行的(它们是脚本),任何根级别的调用(不是方法体)都是在解析时执行的。
class Dog
  puts x
  x=10
end

--output:--
1.rb:2:in `<class:Dog>': undefined local variable or method `x' 
  In this line:
class Dog
  def self.greet
    puts 'hello'
  end

  greet
end

--output:--
hello
class Dog
  greet

  def self.greet
    puts 'hello'
  end

end

--output:--
1.rb:2:in `<class:Dog>': undefined local variable or method `greet'
attr *self.attr_list
def do_math()
  10/0
end