我在Windows 7上学习Ruby(使用版本1.8.6)。
当我尝试运行下面的 stock_stats.rb 程序时,出现以下错误:
C:\Users\Will\Desktop\ruby>ruby stock_stats.rb
stock_stats.rb:1: undefined method `require_relative' for main:Object (NoMethodE
rror)
我有三个v.small代码文件:
stock_stats.rb
require_relative 'csv_reader'
reader = CsvReader.new
ARGV.each do |csv_file_name|
STDERR.puts "Processing #{csv_file_name}"
reader.read_in_csv_data(csv_file_name)
end
puts "Total value = #{reader.total_value_in_stock}"
csv_reader.rb
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
@books_in_stock = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
@books_in_stock << BookInStock.new(row["ISBN"], row["Amount"])
end
end
# later we'll see how to use inject to sum a collection
def total_value_in_stock
sum = 0.0
@books_in_stock.each {|book| sum += book.price}
sum
end
def number_of_each_isbn
# ...
end
end
book_in_stock.rb
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
@books_in_stock = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
@books_in_stock << BookInStock.new(row["ISBN"], row["Amount"])
end
end
# later we'll see how to use inject to sum a collection
def total_value_in_stock
sum = 0.0
@books_in_stock.each {|book| sum += book.price}
sum
end
def number_of_each_isbn
# ...
end
end
提前感谢您的帮助。
答案 0 :(得分:34)
require_relative
。您可以升级Ruby,安装backports gem和require 'backports/1.9.1/kernel/require/relative'
,但最简单的修复方法是将您的需求更改为:
require File.join(File.dirname(__FILE__), 'csv_reader')
答案 1 :(得分:11)
修改强>
回到问这个问题的日子里,它引用了Ruby 1.8.6,其中没有require_relative
。到目前为止,Ruby 1.8.6已经过时,不应该再使用了。
<强>原始强>
根本没有方法名称require_relative
。你可以在那里使用require
。
require_relative
函数包含在Ruby核心库的扩展项目中,可在此处找到:http://www.rubyforge.org/projects/extensions
您应该可以使用gem install extensions
安装它们。
然后在您的代码中添加require_relative
之前的以下行:
require 'extensions/all'