instantiate Foo with ruby? [duplicate]

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


instantiate Foo with ruby? [duplicate]



This question already has an answer here:



How do I instantiate Foo from bar.rb?


bar.rb


# foo.rb
class Foo
def initialize
puts "foo"
end
end


# bar.rb
require 'foo'

Foo.new


$ ruby bar.rb
/home/thufir/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- foo (LoadError)
from /home/thufir/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from bar.rb:2:in `<main>'



Not using modules at the moment. Works fine when Foo is declared inside the same script:


Foo


# bar.rb with Foo declared inside
class Foo
def initialize
puts "foo"
end
end

Foo.new


$ ruby bar.rb
foo



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




1 Answer
1



The stack trace is telling you that your require 'foo' is not working because it can't find the file foo.rb.


require 'foo'


foo.rb



That is because require interprets the argument you give it as an absolute path, or it searches your ruby load path for the specified file.


require



You could resolve this by providing an absolute path to the file. In this case: require '/home/thufir/hello/foo' will work for you.


require '/home/thufir/hello/foo'



You could also use require_relative 'foo', which will search for a file foo.rb in the same directory as your bar.rb.


require_relative 'foo'


foo.rb


bar.rb



https://ruby-doc.org/core-2.4.2/Kernel.html#method-i-require

bLwlgpA0uR8VEB
LZ6zoQqPQm,NgnU,TxWuNSwyPpb6,dQXJsDoB,l83b6,e RELDfiLqBR1SSdcyf,Vsov

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results