17

我正在 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       

提前感谢您的帮助。

4

2 回答 2

34

require_relative doesn't exist in your version of Ruby. You could upgrade Ruby, install the backports gem and require 'backports/1.9.1/kernel/require/relative' but the easiest fix will be to change your require to:

require File.join(File.dirname(__FILE__), 'csv_reader')
于 2010-04-21T07:40:50.480 回答
12

编辑:

早在问这个问题的日子里,它指的是没有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'
于 2010-04-21T07:34:52.013 回答