I'm trying to scrape a table from a website.
status = recPage.css("#MainContent_GridView1").css("tr")[line].css("td")[2].text.chomp.strip
And I got this error for some of the rows.
undefined method `strip' for nil:NilClass (NoMethodError)
or
undefined method `chomp' for nil:NilClass (NoMethodError)
So I thought I could use chomp!.strip! to skip the nil values. But apparently it won't allow me to put those 2 into one line.
Is there a way to modify this?
How about:
status = recPage.css("#MainContent_GridView1").css("tr")[line].css("td")[2].text.chomp.strip rescue ""
It will set status to "";
You're getting these errors because there're nodes with .text=nil, also chomp! and strip! are meant to modify string in-place, not to ignore errors, and they return nil.
Best way is to check the presence of text (not oneliner, thought):
txt = recPage.css("#MainContent_GridView1").css("tr")[line].css("td")[2].text
txt = txt.chomp.strip if txt
In ruby 2.3+ you can use:
recPage.css("#MainContent_GridView1").css("tr")[line].css("td")[2].text&.chomp.&strip
rescue ""-method could lead to errors in the future (if there are some other errors in this line)
If you really want to do it destructively, you can do:
...text&.tap(&:chomp!)&.tap(&:strip!)
Related
So I'm writing a simple Ruby program, essentially a simple ORM. On my "delete" method, I have written the following:
file = "/Users/john/Projects/csv-orm/20180922-test.csv"
def delete id
counter = 0
csv = []
CSV.foreach(file) do |row|
counter += 1
if counter != id
csv << row
end
end
counter = 0
CSV.foreach(file, "w") do |row|
row = csv[counter]
end
end
delete 2
...and I'm running it in an irb session on my terminal (Mac OS X 10.13, ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]) to test it (for example, by pasting in the code above, and then trying delete 2, where the number 2 is the argument passed in for the id parameter), and I get the following error:
Traceback (most recent call last):
4: from /Users/apickle/.rvm/rubies/ruby-2.5.1/bin/irb:11:in `<main>'
3: from (irb):23
2: from (irb):19:in `delete'
1: from /Users/apickle/.rvm/rubies/ruby-2.5.1/lib/ruby/2.5.0/csv.rb:1139:in `foreach'
ArgumentError (wrong number of arguments (given 2, expected 1))
Just to get it out of the way, I have tried testing it in a freshly exited and reopened irb session, and I am typing in require "csv" when I start it up. I'm not sure what to do. :/
EDIT: I've renamed the function to destroy and flfllgpt, and I get the same result - and I have made a simple function that takes a single integer named id and putss it. That function works. It seems to be somehow related to the CSV calls... when I comment those blocks out, it doesn't throw that to me. But I've used them before, too!
It is hard to diagnose the problem without the exact error message, which includes the line number where the error occurs, the method in which the error occurs, the method call for which the error occurs, and the stack trace.
However, there is exactly one place in the code you posted where a method is called with 2 arguments:
CSV.foreach(file, "w") do |row|
# …
end
And indeed, the documentation for CSV::foreach clearly says that CSV::foreach only takes one positional argument, this must be the culprit. There simply is no other place in your code that could possibly raise this exception.
I guess CSV.foreach(file, "w") is the culprit here, because I think what you want to do is open a new file and then write the result? Check this out: https://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#method-c-foreach
If changing it does not help, can you post the full error message? That makes it easier to identify the error.
I'm getting this:
NameError: undefined local variable or method `sentence_count' for main:Object
when I type this:
puts "#{sentence_count / paragraph_count} sentences per paragraph (average)"
Any suggestions?
NameError raises when you try to use an undefined name. Take a moment to read & understand that the error is telling you sentence_count is undefined.
Completely new to rspec here, as will become evident.
The following rspec file fails:
require_relative( 'spec_helper')
describe GenotypingScenario do
it 'should add genes' do
scen = GenotypingScenario.new
gene = Gene.new( "Pcsk9", 989 )
scen.addGene( gene )
expect( gene.id).to eq( 989 )
ct = scen.genes.count
expect (ct).to equal(1)
expect (5).to eq(5)
end
end
Specifically, the last two expect() lines fail, with errors like this:
NoMethodError: undefined method `to' for 1:Fixnum
Yet the first expect line works fine. And gene.id is definitely a FixNum.
Ruby 2.1.2, rspec 3.0.0, RubyMine on Mac OS 10.9.4.
Any thoughts?
The spacing in your last two expect lines are tripping up the Ruby interpreter.
expect (5).to equal(1)
Is evaluated by Ruby as:
expect(5.to(equal(1)))
When what you really mean is:
expect(5).to(equal(1))
It's the return value from calling expect() that has a method to; RSpec isn't extending the Ruby built-in types. So you should change your last two expectations to read as follows:
expect(ct).to equal(1)
expect(5).to eq(5)
I was following a Rails API tutorial with TDD, when I found a line in the tests that expected a json response not to be empty.
This is how I wrote it:
expect(json).not_to_be_empty
And I got that unfriendly NoMethodError: undefined method 'not_to_be_empty'
I came to the accepted answer on this thread and it opened my eyes.
I then changed the line to:
expect(json).not_to be_empty
I know you could still be looking for the difference, well, welcome to RSpec! I removed the underscore in between not_to and be empty to make two words. It worked like ... good code.
I use the dbf gem to read data out of an df file. I wrote some code:
# encoding: UTF-8
require 'dbf'
widgets = DBF::Table.new("patient.dbf")
widgets.each do |record|
puts record.vorname
end
Basically the code works but after ruby writes about 400 record.vorname to the console i get this error:
...
Gisela
G?nter
mycode.rb:5:in `block in <main>': undefined method `vorname' for nil:NilClass (NoM
ethodError)
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/dbf-2.0.6/lib/
dbf/table.rb:101:in `block in each'
......
My question is how can i avoid this error? Therefore it would be intresting why ( how you can see in the error) the record.vorname's with ä,ö,ü are displayed like ?,?,? for eg:
Günter is transformed to G?nter
Thanks
For some reason, your DBF driver returns nil records. You can pretend that this problem doesn't exist by skipping those.
widgets.each do |record|
puts record.vorname if record
end
About your question about the wrong chars, according to the dfb documentation:
Encodings (Code Pages)
dBase supports encoding non-english characters in different formats.
Unfortunately, the format used is not always set, so you may have to
specify it manually. For example, you have a DBF file from Russia and
you are getting bad data. Try using the 'Russion OEM' encoding:
table = DBF::Table.new('dbf/books.dbf', nil, 'cp866')
See doc/supported_encodings.csv for a full list of supported
encodings.
So make sure you use the right encoding to read from the DB.
To avoid the NoMethodError for nil:Nil Class you can probably try this:
require 'dbf'
widgets = DBF::Table.new("patient.dbf")
widgets.each do |record|
puts record.vorname unless record.blank?
end
Doing the Ruby Koans, in the file about_symbols at line 88, I'm not sure of the answer.
This is the code:
def test_symbols_cannot_be_concatenated
# Exceptions will be pondered further farther down the path
assert_raise(what should i put?) do
:cats + :dogs
end
The point of the Ruby Koans is to learn by reading and trying things out.
Open up a terminal and start irb. Then try using the + operator on two symbols. Check the error you get and substitute it as appropriate in the Koans file.
Assuming that your prompt ends in $, that will look something like this:
$ irb
irb(main):001:0> :cats + :dogs
The answer you need will be clear pretty quickly in the error that irb spits out.
To go through step by step in case your completely new to Ruby you could try:
Open up a terminal
Type irb at your prompt to get to the interactive ruby prompt
This is where you can quickly try out different Ruby things
Type the command in question :cats + :dogs
Review the output which will look like
NoMethodError: undefined method `+' for :cats:Symbol
from (irb):1
The name of the exception thrown which is what you are looking for is the first thing e.g. NoMethodError