Skip to content

Instantly share code, notes, and snippets.

@PirosB3
Created August 5, 2014 17:18
Show Gist options
  • Save PirosB3/23c63cbe1c5c3f382820 to your computer and use it in GitHub Desktop.
Save PirosB3/23c63cbe1c5c3f382820 to your computer and use it in GitHub Desktop.
class Expense
attr_accessor :description, :price
def initialize(inputted_description, inputted_price)
# inputted_price is passed as a string, lets
# convert it to int.
# price_to_integer has no @ because its just
# for temporary use, no need to remember it!
price_to_integer = inputted_price.to_i
# Assign inputted_description, that is passed
# in from the constructor, to tne
# local attribute @description
@description = inputted_description
# Assign price_to_integer, that is passed
# in from the constructor, to tne
# local attribute @price.
@price = price_to_integer
end
end
def calculate_total(expense_list)
total = 0
# This is a loop in ruby.
# '.each' assigns each element inside
# the array to the variable 'expense'
# in turn.
expense_list.each do |expense|
# expense here is an Expense object.
# so we can use the 'price'
# and 'desciption' attribute.
total += expense.price
end
# RETURN the value of total. all other
# variables inside this function will be
# ignored. we only care about the end result.
return total
end
def main()
# This is an ARRAY. Think of it as a list of things
# in this case we will be using this to store all our expenses.
all_expenses = []
puts "Expense manager program starts"
puts "enter 'EXIT' as a description if you want to sum all expenses"
loop do
# Read input from the keyboards. gets()
# returns a string containing the inputted
# text
puts "Put your expense description:"
inputted_description = gets().chomp()
# if inputted_description is EXIT, then 'break' the loop.
# if we don't break, the script will continue forever.
if inputted_description == 'EXIT'
# Exits the loop
break
end
puts "Put your expense price:"
inputted_price = gets().chomp()
# Now that we have price and description
# we can create a class INSTANCE.
# Expense.new calls the constructor, that
# accepts to arguments
expense_instance = Expense.new(inputted_description, inputted_price)
# Put it into the array
# http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-push
all_expenses.push(expense_instance)
# Print how many elements are in the array using count
# http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-count
puts "There are now #{all_expenses.count} elements in the list"
end
# Out of the loop!
puts "summing up all expenses.."
# Calling my METHOD. 'calculate_total' returns
# an integer with the total sum of all expenses
total_expenses = calculate_total(all_expenses)
puts "Total expense is: #{total_expenses}"
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment