Skip to content

Instantly share code, notes, and snippets.

@davidbella
Created September 26, 2013 03:28
Show Gist options
  • Save davidbella/6709529 to your computer and use it in GitHub Desktop.
Save davidbella/6709529 to your computer and use it in GitHub Desktop.
Ruby: Exercise in working with arithmetic
# Given:
# 5 songs of the following lengths in seconds
# 223,215,378,324,254
# Goals:
# Assign the length set to variables
# Calculate the Total Length of the Playlists
# Express the Length in Minutes
# Average Song Length in Minutes
# NOTE: I finished this before we were told to not use arrays, etc.
# Went back and did this in a more simple fashion just to get a feel for it
# Left my old code for posterity
# NEW CODE
# Assign the length set to variables
song1 = 223
song2 = 215
song3 = 378
song4 = 324
song5 = 254
# Calculate the Total Length of the Playlists
seconds_total = song1 + song2 + song3 + song4 + song5
puts "Total length in seconds: #{seconds_total}"
# Express the Length in Minutes
# I did this before we went over it at the end of class today - thought it was a neat addition to convert the remainder into seconds so I left this in
minutes = (seconds_total / 60).to_s
minutes_seconds = (seconds_total % 60).to_s
puts "Total length in minutes: #{minutes}:#{minutes_seconds}"
# Average Song Length in Minutes
seconds_avg = seconds_total / 5
minutes_avg = seconds_avg / 60
minutes_seconds_avg = seconds_avg % 60
puts "Average length of 5 songs: #{minutes_avg}:#{minutes_seconds_avg}"
# OLD CODE
# Assign the length set to variables
lengths = [223, 215, 378, 324, 254]
# Calculate the Total Length of the Playlists
seconds_total = lengths.inject(&:+)
puts "Total length in seconds: #{seconds_total}"
# Express the Length in Minutes
minutes_total = (seconds_total / 60).to_s + ':' + (seconds_total % 60).to_s
puts "Total length in minutes: #{minutes_total}"
# Average Song Length in Minutes
minutes_avg = (seconds_total / 5 / 60).to_s + ':' + (seconds_total / 5 % 60).to_s
puts "Average length of 5 songs: #{minutes_avg}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment