gpt4 book ai didi

ruby - 无法加载此类文件 -- write_file

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

我是 Ruby 新手。我刚开始,所以这对我来说很奇怪,因为我来自 Java 和 C# 背景。

write_file.rb 包含:

class Write_file

def write_method(title, text)

@title = title+".txt"
my_file = File.new(@title, 'w')
#my_file.close
puts "Creating file..."

@text = text
my_file = File.open(@title, 'w'){|file|
file.puts @text
}
puts "done!"
end
end

read_file.rb 包含:

class Read_file
def read_method(title)
file = title + ".txt"
File.readlines(file).each do |line|
puts line
end
end
end

write_read.rb 包含:

require "write_file"
require "read_file"
puts "Choose what you want to do :\n1. Write a file\n2. Read a file"
input = gets.to_i
if input.equals? 1
puts "Enter name of file here:"
title = gets.chomp
puts "Enter text here:"
text =gets.chomp
x = Write_file.new
x.write_method(title,text)
puts x
elsif input.equals? 2
puts "Enter name of file to read"
file = gets.chomp
rid = Read_file.new
rid.read_method(file)
puts rid
else puts "Invalid selection"
end

但是我得到以下错误:

/usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- write_file (LoadError)                                            
from /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/ubuntu/workspace/ruby/write_read.rb:1:in `<main>'

最佳答案

当您从命令行运行脚本时,您通常会使用如下命令:ruby my_script.rb .当您这样做时,您将在 ruby​​ 可执行文件的上下文中运行该脚本,并且 ruby​​ 可执行文件需要可以访问任何路径。 Gem 等在可执行文件中注册,因此可以相当容易地访问它们的路径。但是您编写的其他脚本不会为 ruby​​ 可执行文件所知,因此无法通过简单的 require <filename> 访问。 .

因此,为了解决这个问题,您可以做几件事。一种是这样做:

require File.expand_path('write_file', File.dirname(__FILE__))

这告诉 ruby​​ 该文件的位置是相对于正在运行的脚本文件的。

但是,自 ruby​​ 1.9.3 以来,有一个更简单的解决方案;使用 require_relative .这相当于上面的 expand_path 代码:

require_relative 'write_file'

关于ruby - 无法加载此类文件 -- write_file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32416703/

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