Ruby代码顺序

Ruby code order

为什么下面的部分 # def games # @games = games # end 可以在代码的最后(底部)仍然有效?我以为 Ruby 从上到下阅读代码。如果我不在顶部定义games,它不应该报错吗?

class Library
  # def games
  #   @games
  # end
  def initialize(games)
    @games = games
  end
  def add_game(game)
    games << game
  end
  # The following lines should come at the top of this code.
  def games
    @games
  end
end

games = ['WoW','SC2','D3']
lib = Library.new(games)
lib.games #=> WoW,SC2,D3
lib.add_game('Titan')
lib.games #=> WoW,SC2,D3,Titan

定义方法时,ruby不是运行它。在您调用 class.

之后,它仅供实例使用

我通常将我的方法按字母顺序排列,以便随着代码的增长更容易浏览我的代码。这是个人喜好。

Ruby 允许您构建和组织您的 classes/modules 然而对您来说是 logical/beneficial。


澄清一下,Ruby classes 在定义时执行的,但方法不是。

example.rb

class Example
  puts "hello"

  def my_method
    puts "world"
  end
end

运行这

$ ruby example.rb
hello

因为 Ruby 执行 classes,这就是宏在 Ruby classes 中的工作方式。

class Example2
  attr_accessor :foo
end

attr_accessor 是在执行 class 时调用的方法。在这种情况下,attr_acessor 将为 @foo 实例变量设置获取和设置函数。

如果 Ruby 没有执行您的 classes,则必须在某种初始化程序中手动调用此代码。


您需要做的就是学会区分调用方法和定义方法。定义的方法不会自动执行。

之所以如此,是因为 class 是由 Ruby 构建 的方式: [=18= 中的每个实例方法定义] class 在自上而下的解析过程中首先被定义。然后,当您调用每个方法时,重要的是它是否已定义,而不是它的顺序。

话虽如此,如果您要重新定义下面的方法,顺序很重要。则低清晰度优先