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>
Related
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
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 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
I'm new to rails, and I'm getting an error and I can't seem to find were the problem is. Here is the log:
[32651:ERROR] 2012-10-09 13:46:52 :: comparison of Float with Float failed
[32651:ERROR] 2012-10-09 13:46:52 :: /home/sunny/backend/lib/analytics/lifetime.rb:45:in `each'
/home/sunny/backend/lib/analytics/lifetime.rb:45:in `max'
/home/sunny/backend/lib/analytics/lifetime.rb:45:in `max_growth'
/home/sunny/backend/lib/analytics/lifetime.rb:15:in `run'
/home/sunny/backend/lib/analytics/post_analytics.rb:102:in `lifetime'
/home/sunny/backend/lib/analytics/post_analytics.rb:27:in `run`run'
lib/endpoints/posts/index.rb:65:in `block in response'
lib/endpoints/posts/index.rb:62:in `each'
lib/endpoints/posts/index.rb:62:in `response'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/api.rb:163:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/rack/validation/required_param.rb:43:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/rack/params.rb:61:in `block in call'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/rack/validator.rb:40:in `safely'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/rack/params.rb:59:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/rack/async_middleware.rb:73:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/rack-1.4.1/lib/rack/content_length.rb:14:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/async-rack-0.5.1/lib/async_rack/async_callback.rb:114:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/async-rack-0.5.1/lib/async_rack/async_callback.rb:91:in `block in new'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/request.rb:163:in `call'
/usr/local/lib/ruby/gems/1.9.1/gems/goliath-1.0.0.beta.1/lib/goliath/request.rb:163:in `block in process'
Whenever I go to the file and find that row, there is no each, and I can't understand where the problem is. Can anyone help? More than a fix, I want to understand the problem.
Here is the file:
class Lifetime
attr_reader :values
GROWTH_CUT_OFF = 0.10
def initialize(engaged_users_values)
#values = engaged_users_values
end
def run
growths = growth(values)
return [0] if growths.uniq.first == 0 || growths.empty?
max_growth = max_growth(growths)
dead_growth = least_growth(growths, max_growth)
time_diff = time_diff(values.last['end_time'],
values.first['end_time'])
return [time_diff] unless dead_growth
dead_loc = growths.index(dead_growth)
dead_value = values[dead_loc]
lifetime(values.first, dead_value)
end
def time_diff(last, first)
in_minutes(parse_time(last)-parse_time(first))
end
def parse_time(time)
DateTime.parse(time)
end
def growth(values)
values.each_cons(2).map do |one, two|
one_value = one['value'].to_f
two_value = two['value']
((two_value-one_value)/(one_value)*100).round(2)
end
end
def max_growth(growths)
growths.max
end
def least_growth(growths, max_growth)
growth_cut = growth_cut(max_growth)
growths.select {|g| g <= growth_cut}.first
end
def growth_cut(max_growth)
max_growth*GROWTH_CUT_OFF
end
def lifetime(first_value, last_value)
first = parse_time(first_value['end_time'])
last = parse_time(last_value['end_time'])
result = last-first
[in_minutes(result)]
end
def in_minutes(time)
time.to_f*24*60
end
end
If one of both Floats is NaN then you get this message. So, prevent the NaN case.
We can give you more info if you post the exact code of the error (the max_growth method)
I am trying to run the following code:
dupe_groups = Activity.all.group_by { |e| e.non_id_attributes }.select{ |gr| gr.last.size > 1 }
redundant_elements = dupe_groups.map { |group| group.last - [group.last.first] }.flatten
redundant_elements.each(&:destroy)
However, I get the following error:
Activity.find(:all).group_by { |e| e.non_id_attributes }.select{ |gr| gr.last.size > 1 }
NoMethodError: undefined method `last' for #<Hash:0x00000107e505e8>
from (irb):10:in `block in irb_binding'
from (irb):10:in `select'
from (irb):10
from /usr/local/bin/irb:12:in `<main>'
How can I get this fella to work?
When you do a group_by you get a hash, the thing you group by is represented as the keys in the hash so when you select over it you should be doing .select{|key, values| ...} and you can then values.size > 1
Although, when I look at this code, it has a smell to me. What are you actually trying to do?