NameError: uninitialized constant Game - ruby

I have a file Word.rb
class Word
attr_accessor :word, :letters
def initialize (word)
##word = word
#letters = word.split('').map{|letter| {:letter => letter, :hidden => true} }
end
end
and another file Game.rb, which will use Word.rb
require_relative ('./Word.rb')
require 'pry'
class Game
attr_accessor :guesses, :guessed_letters, :words, :current_word
def initialize (words)
#guesses = 0
#guessed_letters = []
#words = words
#current_word = current_word
end
end
And I'm getting the following error:
NameError: uninitialized constant Game
When I try to create a instance of Game like this:
game = Game.new(['hello', 'sunshine', 'chipmunk', 'twitch'])
I just am not sure what I am doing wrong since I am requiring the Word.rb file that Game.rb will need. All files are on the same level, nothing is in a subdirectory. Interestingly, I do not get this error once I comment the require_relative line out (but of course, I need that file required). I have also tried not using require_relative and simply using require as well as a couple other varieties: parens/no parens, file extension/no file extension, etc. How do I properly require this file? I also have a lovely and robust array of words sitting in another file that I would like to require to be used and passed into Game.new().

Look What I did
$ mkdir test
$ cd test
$ gedit Word.rb
# and copied your content and saved
$ gedit Game.rb
# and copied you content and saved
$ irb
After IRB session run I did following
2.1.1 :001 > game = Game.new(['asd'])
NameError: uninitialized constant Game
from (irb):1
from /home/shiva/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'
2.1.1 :002 > require 'game'
LoadError: cannot load such file -- game
2.1.1 :004 > require 'Game.rb'
LoadError: cannot load such file -- Game.rb
2.1.1 :005 > require './Game.rb'
=> true
2.1.1 :006 > game = Game.new(['shiva', 'bhusal'])
=> #<Game:0x00000003085428 #guesses=0, #guessed_letters=[], #words=["shiva", "bhusal"], #current_word=nil>
2.1.1 :007 >
Try like this

Related

Ruby NameError: uninitialized constant

Just started with Ruby - and already stuck :)
I have a module like this:
module Simple
Env = AppEnv::Environment.new { |env, src|
env.test = src.test
}
class Application < Rails::Application
config.autoload_paths += [
"#{config.root}/app/lib/"
]
end
end
Then a class named simplex.rb in the folder /app/lib
class Simplex
def initialize(some)
puts(some)
end
end
Finally a rake task that looks like:
task(:simple => 'simple:default')
namespace(:simple) {
desc('Run simple, first task')
task(:default => :load) do
Simplex.new('okok')
end
}
However I keep getting the error: NameError: uninitialized constant Simplex
I would have thought the autoload_paths would allow Simplex to be found.
Any ideas what I'm doing wrong - seems really trival but I cant see what.
At the top of your Rake file try adding require "#{Rails.root}/lib/simplex" to bring in your Simplex class. Autoload works like this:
mylibrary.rb
puts "I was loaded!"
class MyLibrary
end
IRB
irb(main):001:0> require 'mylibrary'
I was loaded!
=> true
irb(main):001:0> autoload :MyLibrary, 'mylibrary'
=> nil
irb(main):002:0> MyLibrary.new
I was loaded!
=> #<MyLibrary:0x0b1jef>
I would highly recommend reading this article on what the difference between require and autoload is. More importantly, autoload is in the process of being deprecated because of pitfalls regarding it's lazy loading.

Builder's XmlMarkup object loses constants?

I try to upgrade a legacy application from Ruby 1.8.7 to 2.2.3. Afterwards the rendering of builder templates raises errors about unknown classes.
uninitialized constant Builder::XmlMarkup::BigDecimal (NameError)
It seem that within the Builder::XmlMarkup constants like classes disappear.
### example.xml.builder (template) ###
BigDecimal.new('23') # no error
class << xml
def some
data(BigDecimal.new('23')) # raises an error in 2.2.3
end
end
xml.test { xml.some }
### main script ###
require 'rubygems'
require 'builder'
require 'bigdecimal'
def eval_script(file)
xml = Builder::XmlMarkup.new
binding.eval(File.read(file), file)
xml.target!
end
template = File.join(File.dirname(__FILE__), 'example.xml.builder')
puts eval_script(template)
# Ruby 1.8.7 / builder 3.2.0 => <test><data>0.23E2</data></test>
# Ruby 2.2.3 / builder 3.2.2 => ./eval_script.rb:5:in `some': uninitialized constant Builder::XmlMarkup::BigDecimal (NameError)
I found no reason for the behavior. How can I fix the problem?
BTW: I have the same problem with the method lookup, e.g format('%d', 42) which returns the full XML document but doesn't call Kernel.format in Ruby 2.2.3.
I found a workaround overriding const_missing which has to be applied to every template file. It works so far for the legacy application.
### example.xml.builder (template) ###
class << xml
def self.const_missing(name)
super rescue ::Object.const_get(name)
end
def some
data(BigDecimal.new('23'))
end
end
xml.test { xml.some }
But every time the constant BigDecimal is used, it triggers const_missing and then raises a NameError and calls the Object method.

LoadError on require './primes.rb' in terminal

When I do require './primes.rb' in irb I get this:
1.9.3-p392 :004 > require './primes.rb'
LoadError: cannot load such file -- ./primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from (irb):4
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
Here is the primes.rb document:
# primes.rb
require 'debugger'
def prime?(num)
debugger
(1..num).each do |i|
if (num % i) == 0
return false
end
end
end
def primes(num_primes)
ps = []
num = 1
while ps.count < num_primes
primes << num if prime?(num)
end
end
if __FILE__ == $PROGRAM_NAME
puts primes(100)
end
Any suggestions of how to get this to work would be greatly appreciated!
When I do require relative it gives me this:
1.9.3-p392 :010 > require_relative 'primes.rb'
LoadError: cannot infer basepath
from (irb):10:in `require_relative'
from (irb):10
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
When I do the second solution below it gives me this:
1.9.3-p392 :013 > $LOAD_PATH << "."
=> ["/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/x86_64-darwin11.4.2", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/vendor_ruby/1.9.1", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/vendor_ruby/1.9.1/x86_64-darwin11.4.2", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/vendor_ruby", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1", "/Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/x86_64-darwin11.4.2", "."]
1.9.3-p392 :014 > require 'primes.rb'
LoadError: cannot load such file -- primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from (irb):14
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/bin/irb:16:in `<main>'
1.9.3-p392 :015 >
When I try it in pry:
[4] pry(main)> require_relative 'primes.rb'
LoadError: cannot infer basepath
from (pry):2:in `require_relative'
[5] pry(main)> require 'primes.rb'
LoadError: cannot load such file -- primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
[6] pry(main)> .ls
Applications Movies git-completion.bash
Desktop Music rails_projects
Documents Pictures ruby
Downloads Public runwithfriends
Dropbox code shopify
Library dev sites
[7] pry(main)> require 'ruby/app_acad_mini_curriculum/debugging/primes.rb'
LoadError: cannot load such file -- ruby/app_acad_mini_curriculum/debugging/primes.rb
from /Users/RBonhardt/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
Try require_relative
require_relative 'primes.rb'
EDIT:
Note that this will only work from within a script. If you are trying to require this script into an irb session then you will need to provide the full path to primes.rb. The reason is where irb's location is. For instance, try Dir.pwd inside irb and you will see where require_relative is attempting to search for primes.rb.
There are a couple things you could do:
# Just need to require the one file.
require_relative File.join('users', 'yourusername', 'prime_folder', 'prime.rb')
# Many files in the same folder
$LOAD_PATH << File.join('users', 'yourusername', 'prime_folder')
require 'prime.rb'
require 'another_file.rb'
Another option, one that I use, is Pry. It is like irb and is very easy to call from a script. It is a gem so:
gem install pry
At the end of your script, you could do:
if $0 == __FILE__
require 'pry'
binding.pry
end
You would then drop into an irb like REPL where you can test and debug your methods. I can't survive without it.
unlike ruby 1.8, you can't require a file that is in the same folder, because the current folder is not on the load path any longer.
To emulate the behavior of ruby 1.8, you could try
$LOAD_PATH << "."
require 'primes.rb'
However, the correct way to do in ruby 1.9, as #CharlesCaldwell pointed, is using relative_require.
Here is a good discussion of the best way to deal with this.
note that relative_require does not work in irb. You can check the motive on #CharlesCaldwell answer.
But looking in your task question, you should not use irb, you should use pry:
We're going to use two gems. One is called Pry, which is a replacement for irb. You'll have to gem install pry. It's not essential for debugging that you use Pry, but it will make life nicer.
Here is an example using relative require:
[fotanus#thing ~]$ cat primes.rb
# primes.rb
def prime?(num)
(1..num).each do |i|
if (num % i) == 0
return false
end
end
end
def primes(num_primes)
ps = []
num = 1
while ps.count < num_primes
primes << num if prime?(num)
end
end
if __FILE__ == $PROGRAM_NAME
puts primes(100)
end
[fotanus#thing ~]$ cat a.rb
require_relative 'primes.rb'
[fotanus#thing ~]$ ruby a.rb

How to use RSpec expectations in irb

I'd want to use [1,2,3].should include(1) in irb. I tried:
~$ irb
1.9.3p362 :001 > require 'rspec/expectations'
=> true
1.9.3p362 :002 > include RSpec::Matchers
=> Object
1.9.3p362 :003 > [1,2,3].should include(1)
TypeError: wrong argument type Fixnum (expected Module)
from (irb):3:in `include'
from (irb):3
from /home/andrey/.rvm/rubies/ruby-1.9.3-p362/bin/irb:16:in `<main>'
But it doesn't work though it's a valid case. How can I use [1,2,3].should include(1)?
You are close, but calling include on top-level you will be calling Module#include. To get around it you need to remove the original include method so that RSpec's include gets called instead.
First let's figure out where the system include comes from:
> method :include
=> #<Method: main.include>
Ok. It looks like it's defined in main. This is the Ruby top-level object. So let's rename and remove the original include:
> class << self; alias_method :inc, :include; remove_method :include; end
Now we can get down to business:
> require 'rspec'
> inc RSpec::Matchers
> [1,2,3].should include(1)
=> true

How do I use an ActionView::Helper in a Ruby script, outside of Rails?

I am looking to use ActionView::Helpers::NumberHelper from a Ruby script.
What all do I need to require etc.?
~> irb
ruby-1.9.2-p180 :001 > require 'action_view'
=> true
ruby-1.9.2-p180 :002 > ActionView::Base.new.number_to_currency 43
=> "$43.00"
As of Rails 3.2.13, you can do the following:
class MyClass
include ActionView::Helpers::NumberHelper
def my_method
...
number_with_precision(number, precision: 2)
...
end
end
You might need to require 'action_view' too.
Edit: This answer is still valid in Rails 4.2.3.

Resources