Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting the class property #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions lib/challenge.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,34 @@
require "time"

class Challenge
attr_reader :earliest_time
attr_reader :latest_time
attr_reader :peak_year
attr_reader :earliest_time, :latest_time, :peak_year

# Initializer
def initialize(file_path)
@file_path = File.expand_path(file_path)
end

# Parse method which sets the class properties
def parse
# Parse the file located at @file_path and set three attributes:
#
# earliest_time: the earliest time contained within the data set
# latest_time: the latest time contained within the data set
# peak_year: the year with the most number of timestamps contained within the data set
all_rows = {}
peak = {}
# Parsing the file and iterating over the rows
File.open(@file_path, 'r').each_line do |row|
row_time = Time.parse(row)
all_rows[row_time.to_i] = row_time
# Check if year exists in the hash
if(peak.has_key?(row_time.year))
peak[row_time.year] += 1 # if exist Increase the count
else
peak[row_time.year] = 1 # if not assign the one
end
end

# Minimum timestamp in the all_rows will be earliest time
@earliest_time = all_rows[all_rows.keys.min]
# Maximum timestamp in the all_rows will be latest time
@latest_time = all_rows[all_rows.keys.max]
# Peak Year with maximum row counts
@peak_year = peak.key(peak.values.max)
end
end