A basic code in ruby that isn't working for me.... The error specifies
NoMethodError (undefined method `to_i' for
row = row.split(",").map { |x| x.to_i }
EDIT:
NoMethodError (undefined method `to_i' for [["123,123,123,"]]:Array):
app/controllers/sessions_controller.rb:21:in `import'
app/controllers/sessions_controller.rb:20:in `each'
app/controllers/sessions_controller.rb:20:in `import'
app/controllers/sessions_controller.rb:17:in `each'
app/controllers/sessions_controller.rb:17:in `import'
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.7ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.2ms)
you're receiving that error because you're calling the method .to_i on an array, which is wrong since that method is of the String class, source :http://www.ruby-doc.org/core-2.1.0/String.html#method-i-to_i
So in order to fix this we need to take that string from the array so we can turn it into an integer, remember that you started with an array containing an array, so that's why I'm calling .pop twice:
row = [["123, 123, 123"]]
string_of_numbers = row.pop.pop
string_of_numbers.split(",").map {|x| x.to_i }
If it feels too odd try to play with it on irb, that's usually how I try to sort these kinds of things out, don't forget to always refer to the official documentation
Related
I'm attempting to run this code:
def get_linedict(filename,source)
`dwarfdump -l #{source} > dwarfline.txt`
linefile = File.new("dwarfline.txt","r")
match = false
linefile.readlines.each do |line|
puts line
if /uri:/ =~ line
file = line.match(/.*\/(.*)"/)[1]
if file == filename
match = true
end
puts file
puts match
end
end
And when I do I get the following error:
assn4.rb:12:in `block in get_linedict': undefined method `[]' for nil:NilClass (NoMethodError)
from assn4.rb:9:in `each'
from assn4.rb:9:in `get_linedict'
from assn4.rb:126:in `block in <main>'
from assn4.rb:80:in `each'
from assn4.rb:80:in `<main>'
If I change my each loop to only print the lines it's reading, it works fine. As I understand it, the error I'm getting comes from something being nil which shouldn't be, but if that error is coming from the each loop, why am I able to print out the file?
I guess you first have to ask if line.match gets something, before calling an element of the desired array.
line.match(/.*\/(.*)"/)[1]
When you call line.match(/.*\/(.*)"/) the result is nil. Then you attempt to access nil as an Array. That is when you get undefined method []' for nil:NilClass.
And as for this part of your question
but if that error is coming from the each loop, why am I able to print out the file?
The each loop is causing your code to fail and halt when the error occurs. Since you are attempting to print file after the errors, you are actually not printing out file on that iteration of the loop.
Be aware that line might not be nil. Your regular expression is probably just not covering all the cases you think it is, so one of the match calls is failing and returning nil.
I'm trying to get all of my prices in my array of URLS, getting the values with a CSS selector.
The thing is, the method at_css is giving me the following error:
undefined method `at_css' for string (NoMethodError)
Can anyone help me? Thanks
test = ["www.myweb.com/1", "www.myweb.com/2"]
test.each do |item|
Nokogiri::HTML(open(item))
puts item.at_css('.itemprice').text
puts item.at_css('.description').text
puts "Empty Line"
end
The item variable in your block is a string i.e. an element from your test array variable. And strings don't have a to_css method in Ruby. You probably wanted to call the to_css on some Nokogiri-related object.
I think you need the following:
some_var = Nokogiri::HTML(open(item))
some_var.at_css('.itemprice').text
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>'
Dear stackoverflow community,
Beginner's question:
Why do I get the following error?
scraper_sample_2.rb:7:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
>Exit code: 1
Here's my code (copied from a ruby's intro guide):
require "rubygems"
require "crack"
require "open-uri"
URL = "http://www.recovery.gov/pages/GetXmlData.aspx?data=recipientHomeMap"
Crack::XML.parse(open(URL).read)["totals"]["state"].each do |state|
puts ["id", "awarded", "received", "jobs"].map{|f| state[f]}.join(",")
end
Because Crack::XML.parse(open(URL).read)["totals"] is nil. Try to split the call you do on line 7 on several lines and debug each call separately. Maybe the answer you get is not what you expect.
Given the format of the xml returned from your source, Crack::XML.parse(open(URL).read)["totals"] will, as Ivaylo said, return nil. The format of the xml must have changed, as totals are now within /map/view.
To get the expected output, change your code to:
Crack::XML.parse(open(URL).read)["map"]["view"]["totals"]["state"].each do |state|
puts ["id", "awarded", "received", "jobs"].map{|f| state[f]}.join(",")
end
I find this line in the ZenTest source code:
result = #test_mappings.find { |file_re, ignored| filename =~ file_re }
The #test_mappings and result here are both Array object, but I didn't found 'find' method on Array class in ruby doc. I also tried it on irb:
irb(main):014:0> Array.respond_to? :find
=> false
irb(main):015:0> [1,2,3].find
LocalJumpError: no block given
from (irb):15:in `find'
from (irb):15:in `each'
from (irb):15:in `find'
from (irb):15
irb(main):016:0> [1,2,3].find{|x| x>1}
=> 2
Could any one explain it to me? How could find method also return an Array object? thanks in advance.
Array includes the Enumerable module, which adds the find method.
In your example you tested Array.respond_to. This will only return true for class methods of Array. find is an instance method, so respond_to? must be invoked on an instance of the class.
>> a = Array.new
=> []
>> a.respond_to? :find
=> true
Another sometimes useful trick is calling the 'methods' function which lists all the methods available to the instance of the object and using the grep method to filter out for something specific. It also gives you a good picture of what standard methods are provided by base classes without referring to docs.
a = Array.new
=> []
>> a.methods.grep /find/
=> ["find", "find_all"]