gpt4 book ai didi

ruby - 如何将 ruby​​ 类导入主文件?

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:50 25 4
gpt4 key购买 nike

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

NameError: uninitialized constant Book
const_missing at org/jruby/RubyModule.java: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

类代码:

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

最佳答案

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

module Format

def green(input)
puts"\e[32m#{input}[0m\e"
end
end

现在我有了这个文件:

require_relative "format" #<= require the file

include Format #<= include the module

def example
green("this will be green") #<= call the formatting
end

同样的概念也适用于类:

class Example

attr_accessor :input

def initialize(input)
@input = input
end

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

example = Example.new(ARGV[0])

现在我有了主文件:

require_relative "class_example"

example.prompt

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

我希望这对您有所帮助,并回答您的问题。

关于ruby - 如何将 ruby​​ 类导入主文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com