NoMethodError Occurred, undefined method for nil:NilClass - ruby

First of all, I know it has been posted, I've seen most of the question posts but I still don't understand how it works.
So I'm getting the error:
Script 'Terrain Tag Detection ~' line 115: NoMethodError occurred.
undefined method '[]' for nil:NilClass
My 'Terrain Tag Detection ~' Script looks like this: http://pastebin.com/PUypTwJs (can't paste the code here correctly, and yes it's about Pokemon).

That means your #map = WildPokemon.fetch($game_map.map_id) method doesn't return and value and you want to access #map variable.
You can add a check in your code like below:
#map = WildPokemon.fetch($game_map.map_id)
if #map.present?
#enemy = #map[0][rand(#map[0].size)]
#level = #map[1][rand(#map[1].size)]
end

Related

undefined method `gsub' for nil:NilClass ruby

i am a newbie in ruby... I'm trying to convert media into a scorm package using what i found on github but i got an error while trying to run the script in the command prompt undefined method `gsub' for nil:NilClass. I guess it may be due to a defined method. any idea on how i can remove this error ?
dir = ARGV.shift.gsub(/\/+$/, '')
index = nil
media = []
Dir["#{dir}/media/*.json"].each do |file|
id = JSON.parse(File.read(file))
base = file.gsub(/\/media\/.*\.json$/, '')
index = "#{base}/index.html"
name = File.basename file
media.push [name,id]
puts "#{name}: #{id}"
end
As the error says, you are calling the method gsub on an object that is an instance of NilClass, in other words you are calling gsub on nil.
The error message tells you in which method and on which line this happens and how you got to that line of code. You will have to examine the error message to find the place in your code where you are calling gsub on an object that is nil, then you have to examine your code to find out why that object is nil instead of a String as you expect it to.

I have a Ruby undefined local variable or method error

When I try to run this code:
class Message
##messages_sent = 0
def initialize(from, to)
#from = from
#to = to
##messages_sent += 1
end
end
my_message = Message.new(chicago, tokyo)
I get an error that tells me that one of my parameters is undefined local variable. I was just trying to create an instance using Message, and was curious as to why this was not working. I thought this would work as I am calling the class.
Problem
With your current code, you get this error:
undefined local variable or method `chicago' for main:Object (NameError)
because the way you instantiated the Message class:
my_message = Message.new(chicago, tokyo)
chicago and tokyo are interpreted as variable or method that you did not actually define or declare, that's why you got that error.
Solution
I think, you just wanted to pass two string objects (putting chicago and tokyo in the quotes) as the arguments of Message.new call like this:
my_message = Message.new('chicago', 'tokyo')
This will solve your problem.
Hope this makes it clear why you are getting the error and how to solve the problem.
The 'undefined local variable' error is showing up because there's no value associated with chicago or tokyo. If you want to just pass them as strings, wrap them in quotation marks instead, like this:
class Message
##messages_sent = 0
def initialize(from, to)
#from = from
#to = to
##messages_sent += 1
end
end
my_message = Message.new("chicago", "tokyo")

Ruby Unidentified Method for nil No Method Error

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.

undefined method `at_css' for #<String:0x007fe9ac5ae310> (NoMethodError)

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

Ruby. Crack gem. -- in `<main>': undefined method `[]' for nil:NilClass (NoMethodError) --

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

Resources