How do I debug an undefined method for nil class error? - ruby

I'm trying to create a classifier using the cardmagic classifier gem. This is my code:
require 'classifier'
classifications = '1007.09', '1006.03'
traindata = Hash["1007.09" => "ADAPTER- SCREENING FOR VALVES VBS", "1006.03" => "ACTUATOR- LINEAR"]
b = Classifier::Bayes.new classifications
traindata.each do |key, value|
b.train(key, value)
end
But when I run this I get the following error:
Notice: for 10x faster LSI support, please install http://rb-gsl.rubyforge.org/
c:/Ruby192/lib/ruby/gems/1.9.1/gems/classifier-1.3.3/lib/classifier/bayes.rb:27:in `block in train': undefined method `[]' for nil:NilClass (NoMethodError)
from c:/Ruby192/lib/ruby/gems/1.9.1/gems/classifier-1.3.3/lib/classifier/bayes.rb:26:in `each'
from c:/Ruby192/lib/ruby/gems/1.9.1/gems/classifier-1.3.3/lib/classifier/bayes.rb:26:in `train'
from C:/_Chris/Code/classifier/smdclasser.rb:13:in `block in <main>'
from C:/_Chris/Code/classifier/smdclasser.rb:11:in `each'
from C:/_Chris/Code/classifier/smdclasser.rb:11:in `<main>'
This is the source from the gem code:
# Provides a general training method for all categories specified in Bayes#new
# For example:
# b = Classifier::Bayes.new 'This', 'That', 'the_other'
# b.train :this, "This text"
# b.train "that", "That text"
# b.train "The other", "The other text"
def train(category, text)
category = category.prepare_category_name
text.word_hash.each do |word, count|
#categories[category][word] ||= 0
#categories[category][word] += count
#total_words += count
end
end
I am lost where to go to troubleshoot this error, what is the next step I should take?

Classifier::Bayes.new expects an exploded array of values, rather than a single parameter. For example, notice that the sample code uses:
b = Classifier::Bayes.new 'This', 'That', 'the_other'
rather than:
b = Classifier::Bayes.new ['This', 'That', 'the_other']
Pass in the splat version of your classifications array and it should work:
b = Classifier::Bayes.new *classifications

Related

undefined method 'execute' for nil:NilClass

I am making a tool in ruby which can interact with databases.
I am using amalgalite as an adapter for sqlite3.
Code:
require 'amalgalite'
# this is class RQuery
class RQuery
def db_open(db_name)
#db = Amalgalite::Database.new "#{db_name}.db"
make_class
end
def exec_this(query)
#db.execute(query)
end
def make_class
tables_list = exec_this("select name from sqlite_master where type='table'")
tables_list.each do |table|
#class_created = Object.const_set(table[0].capitalize, Class.new)
#class_created.class_eval do
define_singleton_method :first do
RQuery.new.exec_this("select * from #{table[0]} order by #{table[0]}.id ASC limit 1")
end
end
end
end
def eval_this(input)
instance_eval(input)
end
def code
print '>>'
input = gets
exit if input =~ /^q$/
puts eval_this(input)
code
end
end
Now when I am running the code everything works fine until I call table_name.first
It gives output
vbhv#fsociety ~/git/R-Query/bin $ ruby main.rb
Enter the code or q for quit
>>db_open('vbhv')
users
persons
people
programmers
>>Users.first
/home/vbhv/git/R-Query/lib/r-query.rb:36:in `instance_eval': undefined method `execute' for nil:NilClass (NoMethodError)
Did you mean? exec
from /home/vbhv/git/R-Query/lib/r-query.rb:29:in `block (3 levels) in make_class'
from (eval):1:in `eval_this'
from /home/vbhv/git/R-Query/lib/r-query.rb:36:in `instance_eval'
from /home/vbhv/git/R-Query/lib/r-query.rb:36:in `eval_this'
from /home/vbhv/git/R-Query/lib/r-query.rb:43:in `code'
from /home/vbhv/git/R-Query/lib/r-query.rb:44:in `code'
from /home/vbhv/git/R-Query/lib/r-query.rb:44:in `code'
from main.rb:4:in `<main>'
Now the 'execute' function it is talking about is inside amalgalite. What am I doing wrong here?? Thanks in Advance!
The problem in this was that the new class formed dynamically doesn't know about the connection variable '#db'. Hence the code solves the problem.
#class_created.instance_variable_set(:#database, #db)
A big thanks to Jagdeep Singh.

Simple ruby code demonstrating default arguments is throwing name/method error

Seems pretty straightforward. Trying to write a simple code that has a default argument. This throws an error with a name error and method error. Code should be able to take any argument and print the arg and if not arg given print "meat".
Any help why its throwing errors?
def meal_choice( meal = "meat")
puts "#{meal}"
end
Failures:
1) #meal_choice should default to meat
Failure/Error: expect(meal_choice).to eq("meat")
NameError:
undefined local variable or method `meal_choice' for #<RSpec::ExampleGroups::MealChoice:0x007fb4ec159188>
# ./spec/meal_choice_spec.rb:3:in `block (2 levels) in <top (required)>'
2) #meal_choice should allow you to set a meal
Failure/Error: expect(meal_choice("vegan")).to eq("vegan")
NoMethodError:
undefined method `meal_choice' for #<RSpec::ExampleGroups::MealChoice:0x007fb4ec14b0d8>
# ./spec/meal_choice_spec.rb:7:in `block (2 levels) in <top (required)>'
Finished in 0.00125 seconds (files took 0.12294 seconds to load)
2 examples, 2 failures
Failed examples:
rspec ./spec/meal_choice_spec.rb:2 # #meal_choice should default to meat
rspec ./spec/meal_choice_spec.rb:6 # #meal_choice should allow you to set a meal
It is a working code:
[1] pry(main)> def meal_choice( meal = "meat")
[1] pry(main)* puts "#{meal}"
[1] pry(main)* end
#=> :meal_choice
[2] pry(main)> meal_choice
#=> meat
#=> nil
[3] pry(main)> meal_choice(:sdgsdg)
#=> sdgsdg
#=> nil
You must be having a typo in the method call or wrongly calling a method.
You need to make the method do the work without puts:
def meal_choice (meal = "meat")
meal
end

CSV Import RSpec error in Ruby

I am working on an assignment in Ruby.. I had to write RSPEC tests for a method that removes an entry from my address_book app.. and also had to write a test and a method for importing 5 entries from a CSV. In my remove_entry method when I run the Specs it says that I have an undefined method of delete. I have already asked a couple fellow ruby devs and they could not figure it out at first glance. The next error is that when I run the tests for my CSV imports.. The data is not being imported in the proper order. I have spent several hours walking through my code over and over and researching in attempts to fix this.. I am at my wits end.. Any help would be appreciated!
address_book.rb
require_relative 'entry'
require "csv"
class AddressBook
attr_accessor :entries
def initialize
#entries = []
end
def add_entry(name,phone_number,email)
index = 0
#entries.each do |entry|
if name < entry.name
break
end
index += 1
end
#entries.insert(index, Entry.new(name, phone_number, email))
end
def import_from_csv(file_name)
csv_text = File.read(file_name)
csv = CSV.parse(csv_text, headers: true, skip_blanks: true)
csv.each do |row|
row_hash = row.to_hash
add_entry(row_hash["name"], row_hash["phone_number"], row_hash["email"])
#can you clarify what the above is doing
#is the format of row_hash["name"] because it is iterating over a hash or because it is an array?
end
end
def remove_entry(name,phone_number,email)
#entries.each do |entry|
if (name == entry.name) && (email == entry.email) && (phone_number = entry.phone_number)
entry.delete #this line returns an error in my RSPEC test
else
p "Entry does not exist \n Please try again."
end
end
end
end
address_book_spec.rb
require_relative "../models/address_book"
RSpec.describe AddressBook do
let(:book) {AddressBook.new} # => lets us use the book variable in every test
describe "attributes" do
it "should respond to entries" do
# book = AddressBook.new # => Replaced by line 4
expect(book).to respond_to(:entries)
end
it "should initialize entries as an array" do
# book = AddressBook.new # => Replaced by line 4
expect(book.entries).to be_a(Array)
end
it "should initialize entries as an empty array" do
# book = AddressBook.new # => Replaced by line 4
expect(book.entries.size).to eq(0)
end
end
describe "#add_entry" do
it "adds only a single entry to the Address Book" do
# book = AddressBook.new # => Replaced by line 4
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king#lovelace.com')
expect(book.entries.size).to eq(1)
end
it "adds the correct information to entries" do
# book = AddressBook.new # => Replaced by line 4
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king#lovelace.com')
new_entry = book.entries[0]
expect(new_entry.name).to eq('Ada Lovelace')
expect(new_entry.phone_number).to eq('010.012.1815')
expect(new_entry.email).to eq('augusta.king#lovelace.com')
end
end
# added remove entry test
describe "#remove_entry" do
it "should remove a single entry" do
# book = AddressBook.new # => Replaced by line 4
book.add_entry('Austin Thesing', '800.445.8833','austin#thesing.xyz')
expect(book.entries.size).to eq(1)
book.remove_entry('Austin Thesing', '800.445.8833','austin#thesing.xyz')
expect(book.entries.size).to eq(0)
end
end
def check_entry(entry,expected_name,expected_phone_number, expected_email)
expect(entry.name).to eql(expected_name)
expect(entry.phone_number).to eql(expected_phone_number)
expect(entry.email).to eql(expected_email)
end
describe "#import_from_csv" do
it "import an entry from a CSV file" do
book.import_from_csv("entries.csv")
book_size = book.entries.size
expect(book_size).to eq 5 #checks the size of the book
end
it "adds the first entry" do
book.import_from_csv("entries.csv")
entry_one = book.entries[0]
check_entry(entry_one,"Mark Griffo","123456789","mark#bloc.com")
end
it "adds the second entry" do
book.import_from_csv("entries.csv")
entry_two = book.entries[1]
check_entry(entry_two,"Natalie Griffo","123456789","natalie#bloc.com")
end
it "adds the third entry" do
book.import_from_csv("entries.csv")
entry_three = book.entries[2]
check_entry(entry_three, "Steve Thesing", "8583878899", "steve#steve.com")
end
it "adds the fourth entry" do
book.import_from_csv("entries.csv")
entry_four = book.entries[3]
check_entry(entry_four, "Haidee Thesing", "8584458833", "h#thesing.com")
end
it "adds the fifth entry" do
book.import_from_csv("entries.csv")
entry_five = book.entries[4]
check_entry(entry_five, "Olivia Meers", "0987654321", "olivia#meers.com")
end
end
end
Terminal Output/Spec Failures
Austins-MacBook-Pro:address-bloc austinthesing$ rspec spec/address_book_spec.rb
.....F.FFFFF
Failures:
1) AddressBook#remove_entry should remove a single entry
Failure/Error: book.remove_entry('Austin Thesing', '800.445.8833','austin#thesing.xyz')
NoMethodError:
undefined method `delete' for #<Entry:0x007f8e8c1dea08>
# ./models/address_book.rb:37:in `block in remove_entry'
# ./models/address_book.rb:35:in `each'
# ./models/address_book.rb:35:in `remove_entry'
# ./spec/address_book_spec.rb:45:in `block (3 levels) in <top (required)>'
2) AddressBook#import_from_csv adds the first entry
Failure/Error: expect(entry.name).to eql(expected_name)
expected: "Mark Griffo"
got: "Haidee Thesing"
(compared using eql?)
# ./spec/address_book_spec.rb:50:in `check_entry'
# ./spec/address_book_spec.rb:64:in `block (3 levels) in <top (required)>'
3) AddressBook#import_from_csv adds the second entry
Failure/Error: expect(entry.name).to eql(expected_name)
expected: "Natalie Griffo"
got: "Mark Griffo"
(compared using eql?)
# ./spec/address_book_spec.rb:50:in `check_entry'
# ./spec/address_book_spec.rb:69:in `block (3 levels) in <top (required)>'
4) AddressBook#import_from_csv adds the third entry
Failure/Error: expect(entry.name).to eql(expected_name)
expected: "Steve Thesing"
got: "Natalie Griffo"
(compared using eql?)
# ./spec/address_book_spec.rb:50:in `check_entry'
# ./spec/address_book_spec.rb:74:in `block (3 levels) in <top (required)>'
5) AddressBook#import_from_csv adds the fourth entry
Failure/Error: expect(entry.name).to eql(expected_name)
expected: "Haidee Thesing"
got: "Olivia Meers"
(compared using eql?)
# ./spec/address_book_spec.rb:50:in `check_entry'
# ./spec/address_book_spec.rb:79:in `block (3 levels) in <top (required)>'
6) AddressBook#import_from_csv adds the fifth entry
Failure/Error: expect(entry.name).to eql(expected_name)
expected: "Olivia Meers"
got: "Steve Thesing"
(compared using eql?)
# ./spec/address_book_spec.rb:50:in `check_entry'
# ./spec/address_book_spec.rb:84:in `block (3 levels) in <top (required)>'
Finished in 0.0176 seconds (files took 0.08714 seconds to load)
12 examples, 6 failures
Failed examples:
rspec ./spec/address_book_spec.rb:40 # AddressBook#remove_entry should remove a single entry
rspec ./spec/address_book_spec.rb:61 # AddressBook#import_from_csv adds the first entry
rspec ./spec/address_book_spec.rb:66 # AddressBook#import_from_csv adds the second entry
rspec ./spec/address_book_spec.rb:71 # AddressBook#import_from_csv adds the third entry
rspec ./spec/address_book_spec.rb:76 # AddressBook#import_from_csv adds the fourth entry
rspec ./spec/address_book_spec.rb:81 # AddressBook#import_from_csv adds the fifth entry
First test is failing because the delete method is being used incorrectly:
entry.delete #this line returns an error in my RSPEC test
needs to be
#entries.delete(entry)
Entries are being inserted in a scrambled fashion because you are using break where you probably want
next
(I suppose that loop is supposed to insert in alphabetical order.)
break command terminates the full each block, so no more iterations are executed if there is one name of higher alphabetical order, next just skips to the next iteration.
That should be it

Unexpected Method Call

I'm using mongomapper to store pages in a db, and I index them first. In the index method, I loop through each word, and check to see if it is already in the words hashmap. If not, I add an empty array to the hash, then push its location to the array.
def index_words
#words = self.body.split(" ")
#words.each_with_index do |word,i|
if self.words[word.stem].nil?
self.words[word.stem] = []
end
puts "Called from #{caller[0]}"
self.words[word.stem].push(i)
end
end
When I run this, I get an undefined method error, saying that self.words[word.stem] is nil. Furthermore, this method is actually being called from the loop, when it's only called once in the constructor:
def initialize(*args)
super
index_words
end
The error message is:
p = Page.new({author: 'Michael',url: 'michaelfine.me',title: 'Michael Fine',body: 'Body Text'})
called fromPage.rb:19:in `each'
NoMethodError: undefined method `push' for nil:NilClass
from Page.rb:24:in `block in index_words'
from Page.rb:19:in `each'
from Page.rb:19:in `each_with_index'
from Page.rb:19:in `index_words'
from Page.rb:14:in `initialize'
from (irb):103:in `new'
from (irb):103
from /Users/Michael/.rvm/rubies/ruby-1.9.3-p286/bin/irb:16:in `<main>'

Ruby error with CSV and <<

Well, I think the code speaks out for itself :)
# book_in_stock.rb
class BookinStock
attr_reader :isbn, :price
def initialize(isbn, price)
#isbn = isbn
#price = Float(price)
end
end
# csv_reader.rb
require 'csv'
class CsvReader
def initialize
#book_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
# stock_stats.rb
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}"
When running I get:
# +search/pickaxe/csv $ ruby1.9.1 test.rb data.csv
# [+] Processing data.csv
# test.rb:23:in `block in read_in_csv_data': undefined method `<<' for nil:NilCla
# ss (NoMethodError)
# from /usr/lib/ruby/1.9.1/csv.rb:1760:in `each'
# from /usr/lib/ruby/1.9.1/csv.rb:1196:in `block in foreach'
# from /usr/lib/ruby/1.9.1/csv.rb:1334:in `open'
# from /usr/lib/ruby/1.9.1/csv.rb:1195:in `foreach'
# from test.rb:22:in `read_in_csv_data'
# from test.rb:46:in `block in <main>'
# from test.rb:44:in `each'
# from test.rb:44:in `<main>'
What've I done wrong?
'#books_in_stock' != '#book_in_stock' # !
(typo)
You have a typo in the initialize function (#book_in_store insteadn of #books_in_store). Is that it?
By the way, the sum of the prices can be done with inject in one line
#books_in_stock.inject(0) { |sum, book| sum + book.price }
If you run the command with ruby -w, it'll turn on warnings, and the interpreter will explain what went wrong:
$ ruby -w book_in_stock.rb
book_in_stock.rb:28: warning: instance variable #books_in_stock not initialized
book_in_stock.rb:28:in `total_value_in_stock': undefined method `each' for nil:NilClass (NoMethodError)
from book_in_stock.rb:47:in `<main>'

Resources