在Ruby代码中放置“require”的位置?

时间:2014-01-16 12:49:18

标签: ruby require ruby-2.0

我使用的是Ruby 2.0,我有两个文件:hello.rb& assets/display.rb

hello.rb的

class Hello
  def self.run_it(name)
    ui = Display.new(name)
    ui.say_hi
  end
end

require_relative "assets/display"

Hello.run_it("Someone")

资产/ display.rb

class Hello::Display
  def initialize(name = "World")
    @name = name
  end

  def say_hi  
    puts "Hello #{@name}"  
  end
end

如果在hello.rb中我在require_relative "assets/display"(第1行)之前移动class Helloruby hello.rb会输出uninitialized constant错误。这是为什么?在需要外部文件时,最佳做法是什么?require_relative这个简短示例中的require正确方法(vs require "./some_file"和{{1}})是什么?

3 个答案:

答案 0 :(得分:3)

标准做法是将所有或大部分require语句放在文件的顶部。应该设计文件,以便尽可能减少对其他文件的依赖。

您遇到的问题是您已将文件display.rb设计为依赖于班级Hello

当你这样说时:

class Hello::Display
end

与以下内容相同:

class Hello
  class Display
  end
end

但不同之处在于,在第一种情况下需要先定义Hello,然后才能说出Hello::Display。由于当您将require放在文件顶部时未定义Hello,您将收到错误。

你可以这样解决:

class Hello
   class Display
     # ..your Display code here..
   end
end

或者像这样:

# Predefine Hello as a class name
class Hello
end

class Hello::Display
  # ..your Display code here..
end

答案 1 :(得分:1)

如果在hello.rb的开头包含文件display.rb,那么当ruby解释器遇到class Hello::Display时,它会在之前的某处定义Hello。但此时,尚未定义类Hello,因此您会看到错误。

答案 2 :(得分:1)

出现此错误的原因是您正在尝试在Hello类中定义一个类,此类此时尚未定义。只需将名称分为两类:

class Hello
  class Display
    def initialize(name = "World")
      @name = name
    end

    def say_hi  
      puts "Hello #{@name}"  
    end
  end
end

这样你就可以一次定义两个类(稍后你可以打开Hello类)