0
#stacklike.rb file
module Stacklike
  def stack
    @stack ||= []
  end
​
  def add_to_stack(obj)
    stack.push(obj)
  end
​
  def take_from_stack
    stack.pop
  end
end
​
#stack.rb file
require "stacklike"
​
class Stack
  include Stacklike
end
​
s = Stack.new
​
s.add_to_stack("item one")
s.add_to_stack("item two")
s.add_to_stack("item three")
​
puts "Objects currently on the stack:"
puts s.stack
​
taken = s.take_from_stack
puts "Removed this object:"
puts taken
​
puts "Now on stack:"
puts s.stack
​
​
ruby stack.rb
=>
/Users/jchu773/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- stacklike.rb (LoadError)
    from /Users/jchu773/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from stack.rb:1:in `<main>'

Hi all, Im reading David Black's Well Grounded Rubyist right now and I'm currently learning Modules. I'm following along in his exercise examples but whenever I use the #require method, the above error pops up, anyone know why?

Jason Chu
  • 355
  • 1
  • 2
  • 14
  • Does it work when you change `require` to `require_relative`? If so, and you want to know what the difference is, [this SO Q&A](http://stackoverflow.com/q/3672586/567863) is a great resource. – Paul Fioravanti Apr 13 '16 at 23:12

2 Answers2

0

require_relative requires files from a relative path

require file needs you to specify the exact(absolute) path

for ex. I have an app.rb and a module.rb in one directory(c:/users/ruby/app/this_app/) require_relative looks for the module file where you ran app.rb require_relative "module" looks into the directory where I ran app.rb(this_app/)

require "module(.rb)" might even need you to specify the full path and extension name I believe. I'm not sure on the extension name but I'm 100% sure it needs the full absolute path

require "/users/ruby/app/this_app/module(.rb)"

powerup7
  • 120
  • 3
  • 14
0

require needs an absolute path, but you can use require from the current directory with require "./stacklike". require_relative uses a path relative to the current directory, so require_relative "stacklike" would also work.

Generally speaking source files are loaded by adding a directory to the Ruby load path, then doing require "source_file". Rubygems enhances require so that it can load files from your installed gems; that is why the error message:

rubygems/core_ext/kernel_require.rb:54:in 'require': cannot load such file -- stacklike.rb (LoadError)

comes from Rubygems, which assumes you are trying to load a gem named 'stacklike'.

zetetic
  • 47,184
  • 10
  • 111
  • 119