Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

require - Why doesn't relative_require work on Ruby 1.8.6?

I'm learning Ruby (using version 1.8.6) on Windows 7.

When I try to run the stock_stats.rb program below, I get the following error:

C:UsersWillDesktop
uby>ruby stock_stats.rb
stock_stats.rb:1: undefined method `require_relative' for main:Object (NoMethodE
rror)

I have three v.small code files:

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       

Thanks in advance for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...