Getting error undefined method `[]' for nil:NilClass (NoMethodError) - ruby-on-rails

Here is the code
class Tech
attr_reader :content, :tech_hash
#tech_hash = Hash.new(0)
def initialize(content)
#content = content
showTech(content)
end
def showTech(content)
content.split.each do |word|
#tech_hash[word] += 1
end
#tech_hash = #tech_hash.sort_by{|k,v| -v}.to_h
p #tech_hash
end
end
class Digital
def analyze()
File.foreach('test.txt') do |content|
ob = Tech.new(content)
end
end
end
digi = Digital.new()
digi.analyze()
Here is the error
D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:10:in `block in showTech': undefined method `[]' for nil:NilClass (NoMethodError)
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `each'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `showTech'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:6:in `initialize'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `new'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `block in analyze'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `foreach'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `analyze'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:29:in `<main>'

#tech_hash is defined outside of an instance method, what makes it a class variable. Therefore within showTech there is still no #tech_hash instance variable defined and therefore it returns nil
Just move #tech_hash into the initialize method to initialize an instance variable:
def initialize(content)
#content = content
#tech_hash = Hash.new(0)
showTech(content)
end

Related

How can I fix this issue in Ruby?

I have the following code, the purpose is to create read, and add to JSON file in Ruby
I will copy the code and the error am getting down here
game_module.rb
require 'json'
require_relative '../classes/game'
require 'date'
def load_games
data = []
file = './json_files/games.json'
if File.exist?(file)
JSON.parse(File.read(file)).each do |game|
publish_date = game['publish_date'] ? Date.parse(game['publish_date']) : nil
last_played_at = game['last_played_date'] ? Date.parse(game['last_played_date']) : nil
data.push(Game.new(publish_date, game['multiplayer'], last_played_at, archived: game['archived']))
end
else
File.write('./json_files/games.json', [])
end
data
end
def create_game
data = []
#games.each do |game|
data.push(game.publish_date, game.multiplayer, game.last_played_date, archived: game.archived)
end
File.write('./json_files/games.json', JSON.generate(data))
end
game.rb file
require_relative './items'
require 'date'
class Game < Item
attr_accessor :multiplayer, :last_played_date
def initialize(date, multiplayer, last_played_date, archived: false, id: nil)
super(id, date, archived: archived)
#multiplayer = multiplayer
#last_played_date = Date.parse(last_played_date)
end
def can_be_archived?
current_date = Date.today
super && (current_date.year - #last_played_date.year) > 2
end
end
json file
[{"publish_date":"2022-01-01", "multiplayer": false, "last_played_date": "2021-12-31","archived": false}]
the error text
no implicit conversion of Date into String (TypeError)
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/src/classes/items.rb:8:in `initialize'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/src/classes/game.rb:8:in `initialize'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/src/modules/game_module.rb:12:in `new'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/src/modules/game_module.rb:12:in `block in load_games'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/src/modules/game_module.rb:9:in `each'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/src/modules/game_module.rb:9:in `load_games'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/app.rb:22:in `<class:App>'
from /home/shaker/Desktop/microverse - backend /Ruby-Catalog-of-my-things/app.rb:5:in `<top (required)>'
from main.rb:1:in `require_relative'
from main.rb:1:in `<main>

Ruby : Getting error []': no implicit conversion of String into Integer (TypeError)

class LineAnalyzer
##highest_wf_count = 0
##highest_wf_words = Hash.new(0)
def initialize(content, line_number)
#content = content
#line_number = line_number
calculate_word_frequency(content)
end
def calculate_word_frequency(content)
content.split.each do |word|
##highest_wf_words[word.downcase] +=1
end
##highest_wf_words = ##highest_wf_words.sort_by{|k,v| -v}
end
end
class Solution
def initialize()
#analyzers = Array.new
#highest_count_words_across_lines = Array.new
end
def analyze_file()
#line_number = 0
File.foreach('test.txt') do |content|
#line_number += 1
#line = LineAnalyzer.new(content,#line_number)
#analyzers.<<(#line)
end
end
end
When trying to create LineAnalyzer object and passing values, getting this error in:
#line = LineAnalyzer.new(content,#line_number)
This is what I getting:
Max-Word-Freq/module2_assignment.rb:34:in `calculate_word_frequency'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:25:in `initialize'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `new'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:68:in `block in analyze_file'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `foreach'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/module2_assignment.rb:66:in `analyze_file'
from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/solution.rb:10:in `<main>'
You have this error because you are trying to use an Array like a Hash.
On this line :
##highest_wf_words = ##highest_wf_words.sort_by{|k,v| -v}
In the first time ##highest_wf_words is indeed a Hash but the sort_by method is returning an Array. So when you use it again you have an error.
If you want to sort your hash by value you can do this :
##highest_wf_words = Hash[##highest_wf_words.sort]
# Or reverse it
##highest_wf_words = Hash[##highest_wf_words.sort.reverse]
Look at this for further explanation : Hash::[]

I am using https://github.com/tyrauber/stock_quote to fetch stock data. However I am getting below mentioned error while doing so

I am new to ruby on rails. :(
while doing a search I am getting StockQuote::NoDataForStockError in StocksController#search ...........................
My model
class Stock < ActiveRecord::Base
def self.find_by_ticker(ticker_symbol)
where(ticker: ticker_symbol).first
end
def self.new_from_lookup(ticker_symbol)
looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
return nil unless looked_up_stock.name
new_stock = new(ticker: looked_up_stock, name: looked_up_stock.name)
new_stock.last_price = new_stock.price
new_stock
end
def price
closing_price = StockQuote::Stock.quote(ticker).close
return "#{closing_price} (closing)" if closing_price
opening_price = StockQuote::Stock.quote(ticker).open
return "#{opening_price (opening)}" if opening_price
"Unavailable"
end
end
Errors I am getting in console while doing a search.
StockQuote::NoDataForStockError: StockQuote::NoDataForStockError
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/stock_quote-1.2.3/lib/stock_q
uote/stock.rb:134:in `parse'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/stock_quote-1.2.3/lib/stock_q
uote/stock.rb:86:in `block in quote'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rest-client-1.6.7/lib/restcli
ent/request.rb:228:in `call'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rest-client-1.6.7/lib/restcli
ent/request.rb:228:in `process_result'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rest-client-1.6.7/lib/restcli
ent/request.rb:178:in `block in transmit'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/net/http.rb:853:in `start'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rest-client-1.6.7/lib/restcli
ent/request.rb:172:in `transmit'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rest-client-1.6.7/lib/restcli
ent/request.rb:64:in `execute'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/rest-client-1.6.7/lib/restcli
ent/request.rb:33:in `execute'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/stock_quote-1.2.3/lib/stock_q
uote/stock.rb:84:in `quote'
from C:/Sites/tracker/app/models/stock.rb:19:in `price'
from C:/Sites/tracker/app/models/stock.rb:14:in `new_from_lookup'
from (irb):9
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/co
mmands/console.rb:110:in `start'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/co
mmands/console.rb:9:in `start'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/co
mmands/commands_tasks.rb:68:in `console'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/co
mmands/commands_tasks.rb:39:in `run_command!'
from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/co
mmands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
If you look at the code for that gem you can see that a StockQuote::NoDataForStockError is returned when the response code is not 200. You'll need to delve into what it doesnt like about the data you are providing. For example you should be able to query the response a bit more and at least determine what url is being sent.
The solution for page interrupting is to use begin rescue blocks every time when we call methods from StockQuote module. In begin part of block use regular call and in rescue part set value to nil and in that case return value 'Unavailable' and similar.begin rescue in Ruby is like try catch in Java. Example:
def price
begin
closing_price = StockQuote::Stock.quote(ticker).close
rescue
closing_price = nil
end
return "#{closing_price} (Closing)" if closing_price
begin
opening_price = StockQuote::Stock.quote(ticker).open
rescue
opening_price = nil
end
return "#{opening_price} (Opening)" if opening_price
'Unavailable'
end

Ruby where clause is returning nil object? ActionView::Template::Error (undefined method `each' for nil:NilClass):

I'm getting the follow error:
ActionView::Template::Error (undefined method `each' for nil:NilClass):
Here is the where clause, the first one works.
def self.unpaid
ARequest.where(:paid_on => nil).in(:status => [ARequest::TRANS_COMPLETE,ARequest::CANCELLED_BY]).gt(:total_owed_to_driver_in_cents => 0).asc(:assigned_driver_id).asc(:timestamp_requested)
end
This does NOT work.
def self.allcall
longtimeago = Time.now - 60.day
yesterday = Time.now - 1.day
ARequest.where(["paid_on >= ? AND paid_on <= ?", longtimeago.beginning_of_day, yesterday.end_of_day]).in(:status => [ARequest::TRANS_COMPLETE,ARequest::CANCELLED_BY]).gt(:total_owed => 0).asc(:assigned_driver_id).asc(:timestamp_requested)
end
The above throws this error:
ActionView::Template::Error (undefined method `each' for nil:NilClass):
CONTROLLER CODE
def allcalls
ensure_root
#calls = ARequest.allcall
end
ROUTE
get "sme/allcalls"
Just try to change
where(["paid_on >= ? AND paid_on <= ?", longtimeago.beginning_of_day, yesterday.end_of_day])
to
where("paid_on >= ? AND paid_on <= ?", longtimeago.beginning_of_day, yesterday.end_of_day)

NoMethodError: undefined method `delete' for nil:NilClass

i get this
irb(main):001:0> Match.create(id: 401381886)
(0.0ms) begin transaction
Match Exists (1.0ms) SELECT 1 AS one FROM "matches" WHERE "matches"."id" = 401381886 LI
MIT 1
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 4294967295
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 105382029
(0.0ms) rollback transaction
NoMethodError: undefined method `delete' for nil:NilClass
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/attribute_methods/write.rb:33:in `write_attribute'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/attribute_methods/dirty.rb:70:in `write_attribute'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/attribute_methods/write.rb:19:in `__temp__57375627f59646='
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/attribute_methods.rb:126:in `method_missing'
from W:/projects/rails/private/dota2monster/app/models/match_performance.rb:13:in
`block in getData'
from W:/projects/rails/private/dota2monster/app/models/match_performance.rb:11:in
`each'
from W:/projects/rails/private/dota2monster/app/models/match_performance.rb:11:in
`getData'
from W:/projects/rails/private/dota2monster/app/models/match_performance.rb:7:in `
initialize'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/inheritance.rb:27:in `new'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/inheritance.rb:27:in `new'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/persistence.rb:36:in `create'
from W:/projects/rails/private/dota2monster/app/models/match.rb:25:in `getData'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/
active_support/callbacks.rb:387:in `_run__512386826__save__callbacks'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activesupport-4.0.0/lib/
active_support/callbacks.rb:80:in `run_callbacks'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/callbacks.rb:299:in `create_or_update'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/persistence.rb:106:in `save'
... 3 levels...
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/transactions.rb:326:in `block in with_transaction_returning_status'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/connection_adapters/abstract/database_statements.rb:202:in `block in transact
ion'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/connection_adapters/abstract/database_statements.rb:210:in `within_new_transa
ction'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/connection_adapters/abstract/database_statements.rb:202:in `transaction'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/transactions.rb:209:in `transaction'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/transactions.rb:323:in `with_transaction_returning_status'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/transactions.rb:270:in `block in save'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/transactions.rb:281:in `rollback_active_record_state!'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/transactions.rb:269:in `save'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.0/lib/a
ctive_record/persistence.rb:37:in `create'
from (irb):1
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails
/commands/console.rb:90:in `start'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails
/commands/console.rb:9:in `start'
from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails
/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
Match Model
class Match < ActiveRecord::Base
include HTTParty
has_many :matchperformances
has_many :users, through: :matchperformances
before_save :getData
validates :id, presence: true, uniqueness: true
def response(api_id)
base_url = "http://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=5F45B214200C4274114FE87E3A62E7B8&match_id="
url = base_url + api_id.to_s
response = HTTParty.get(url)
end
def getData
response = response(self.id)
match = response["result"]
self.radiant_win = match["radiant_win"]
self.duration = match["duration"]
self.start_time = match["start_time"]
self.lobby_type = match["lobby_type"]
self.human_players = match["human_players"]
self.leagueid = match["leagueid"]
self.game_mode = match["game_mode"]
MatchPerformance.create(response)
end
end
User Model
class User < ActiveRecord::Base
has_many :match_performances
has_many :matches, through: :match_performances
end
MatchPerformance Model
class MatchPerformance < ActiveRecord::Base
belongs_to :user
belongs_to :match
def initialize(response)
#response = response
getData(#response)
end
def getData(response)
response["result"]["players"].each do |player|
unless User.where(id: player["account_id"]).blank?
self.user_id = player["account_id"]
self.match_id = response["result"]["match_id"]
self.player_slot = player["player_slot"]
self.hero_id = player["hero_id"]
self.item_0 = player["item_0"]
self.item_1 = player["item_1"]
self.item_2 = player["item_2"]
self.item_3 = player["item_3"]
self.item_4 = player["item_4"]
self.item_5 = player["item_5"]
self.kills = player["kills"]
self.deaths = player["deaths"]
self.assits = player["assits"]
self.leaver_status = player["leaver_status"]
self.gold = player["gold"]
self.last_hits = player["last_hits"]
self.denies = player["denies"]
self.gold_per_min = player["gold_per_min"]
end
end
end
end
I try to make a dota2 api.
When a user gives the match id, it gets the data from the api, and stores it in the db, so i don't need to bash their api
i think the problem is with
def initialize(response)
#response = response
getData(#response)
end
Change it to
def initialize(response)
super
#response = response
getData(#response)
end
According to this blog post Rails: Don't override initialize on ActiveRecord objects You shouldn't rely on this method for ActiveRecord objects.

Resources