HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Using Ruby to record tasks

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
recordtasksusingruby

Problem

I started writing this program to get a better understanding of different aspects of Ruby. I tried to follow the ruby style guide here.

What it's supposed to do is take the exercises/tasks you give it, and record those tasks. It uses a record of those tasks to automatically create/update the header row of a .csv file for the month, and to automatically create a row for every day that information (repetitions of a given exercise) is inputted. I know this program may seem a little useless, after all, many of us own excel, and currently it just gets input from gets, but I was thinking I might do more with it in the future.

I wrote two versions:

Version one:

```
# Requires
require "date"
require "csv"

# Functions
def standardize(string)
# 'Standardizes' strings so that "word word" becomes "Word-Word"
new_string = ""
string_parts = string.strip.split
string_parts.each do |part|
part.capitalize!
new_string << part + "-"
end
return new_string[0..-2]
end

def ensure_file(file_path)
# Checks if a file exists and creates it if it doesn't exist
if !File.file?(file_path)
file = File.new(file_path, "w")
file.close
end
end

def overwrite_csv(path, csv_table)
# Overwrites a CSV file
# Made this a function so I can change how I do it throughout the file
# from one place
CSV.open(path, "w") do |csv_file|
csv_table.each { |row| csv_file << row }
end
end

# Constants
KNOWN_EXERCISES = "known_exercises.txt"
MONTH_FILE = Date::MONTHNAMES[Date.today.month] + ".csv"

# Gets an array of known exercises
ensure_file(KNOWN_EXERCISES)
exercises = []
File.foreach(KNOWN_EXERCISES) do |exercise|
exercise.strip!
exercise != "" ? exercises << exercise.strip : nil
end

# Gets information from the user
print "Exercise: "
exercise = standardize(gets.strip)
print "Repetitions: "
reps = gets.strip

# Checks if the exercise is in the known exercises file, writes it in if not
if !exercises.include?(exercise)
File.open(KNOWN_EXERCISES, "a") do |kno

Solution

Sorry I don't have time to review the full program, but here's a much simpler replacement for the standardize method. Note strip is a redundant if you're then going to be splitting on white space:

def standardize(string)
  # 'Standardizes' strings so that "word word" becomes "Word-Word"
  string.split.map(&:capitalize).join('-')
end

Code Snippets

def standardize(string)
  # 'Standardizes' strings so that "word word" becomes "Word-Word"
  string.split.map(&:capitalize).join('-')
end

Context

StackExchange Code Review Q#131754, answer score: 3

Revisions (0)

No revisions yet.