Skip to content

Instantly share code, notes, and snippets.

@chrisbodhi
Created February 21, 2014 15:59
Show Gist options
  • Save chrisbodhi/9136897 to your computer and use it in GitHub Desktop.
Save chrisbodhi/9136897 to your computer and use it in GitHub Desktop.
Take input from a text file & output the response to a new text file
# Open the source file & store each element in an array
# (sans the newline character)
def parse_file(file)
arr = []
list = File.open(file)
list.each do |item|
if item.include? "\n"
arr << item.chomp
else
arr << item
end
end
arr
end
# Return array of letter and number pairs split at underscore
# Called in get_count
def split_(elem)
pos = elem.index('_')
letter = elem[0..pos - 1]
num = elem[pos + 1..-1].to_i
[letter, num]
end
# Populate a new hash with letters while counting and math-ing
# Called in get_count
def checker(new_hash, key, value = 1)
if new_hash[key]
new_hash[key] += value
else
new_hash[key] = value
end
end
# Make the math while placing pairs into a hash
def get_count(arr)
hash_start = {}
arr.each do |elem|
if elem.include? '_'
letter = split_(elem)[0]
num = split_(elem)[1]
checker(hash_start, letter, num)
else
checker(hash_start, elem)
end
end
hash_start
end
# Split hashes into two: one with a count of 1, one with a count of more than 1
def sort_hash(almost_ready_hash)
multi_hash = {}
single_hash = {}
almost_ready_hash.each do |k, v|
if v > 1
multi_hash[k] = v
else
single_hash[k] = v
end
end
[multi_hash, single_hash]
end
# Sort the hashes for final presentation
def present(hashes)
final_hash = {}
hashes[0].sort_by{ |k, v| v}.reverse.each do |k, v|
final_hash[k] = v
end
hashes[1].each do |k, v|
final_hash[k] = v
end
final_hash.to_a
end
# Save the response to a new text file
def write_file(file, input)
File.open(file, "a") do |f|
input.each do |e|
f.write("#{e[0]} #{e[1]}\n")
end
end
end
parsed = parse_file('list.txt')
counted = get_count(parsed)
sorted = sort_hash(counted)
write_file('new.txt', present(sorted))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment