如何将ruby类导入主文件?

Fri*_*iso 9 ruby

我正在尝试学习如何使用Ruby编程,我想为单独的类创建单独的文件,但是当我这样做时,我得到以下消息:

NameError:未初始化的常量
在org/jruby/RubyModule.java上预订const_missing:2677

(root)at /Users/Friso/Documents/Projects/RubyApplication1/lib/main.rb:1

但是,如果我将类直接放入主文件中,它就可以工作.我怎么解决这个问题?

主要代码:

book1 = Book.new("1234", "Hello", "Ruby")
book2 = Book.new("4321", "World", "Rails")

book1.to_string
book2.to_string
Run Code Online (Sandbox Code Playgroud)

班级代码:

class Book
  def initialize(isbn,title,author)
    @book_isbn=isbn
    @book_title=title
    @book_author=author
  end

  def to_string
    puts "Title: #@book_title"
    puts "Author: #@book_author"
    puts "ISBN: #@book_isbn"
  end
end
Run Code Online (Sandbox Code Playgroud)

13a*_*aal 19

为了将类,模块等包含到您必须使用的其他文件中require_relativerequire(require_relative更多Rubyish.)例如这个模块:

module Format

  def green(input)
    puts"\e[32m#{input}[0m\e"
  end
end
Run Code Online (Sandbox Code Playgroud)

现在我有这个文件:

require_relative "format" #<= require the file

include Format #<= include the module

def example
  green("this will be green") #<= call the formatting 
end
Run Code Online (Sandbox Code Playgroud)

课程也采用相同的概念:

class Example

  attr_accessor :input

  def initialize(input)
    @input = input
  end

  def prompt
    print "#{@input}: "
    gets.chomp
  end
end

example = Example.new(ARGV[0])
Run Code Online (Sandbox Code Playgroud)

现在我有了主文件:

require_relative "class_example"

example.prompt
Run Code Online (Sandbox Code Playgroud)

要从另一个文件中调用任何类或模块,您必须要求它.

我希望这会有所帮助,并回答你的问题.


Kei*_*ett 8

您需要指示Ruby运行时加载包含Book类的文件.您可以使用require或执行此操作require_relative.

在这种情况下,后者更适合您,因为它相对于require指定包含该文件的文件的目录加载文件.因为那可能是同一个目录,你可以只需要调用文件名而不需要require_relative扩展名.

您可以谷歌'require vs require_relative ruby​​'来了解有关差异的更多信息.