Skip to content

Instantly share code, notes, and snippets.

@pjb3
Last active August 29, 2015 14:06
Show Gist options
  • Save pjb3/ad4d10960754ef479746 to your computer and use it in GitHub Desktop.
Save pjb3/ad4d10960754ef479746 to your computer and use it in GitHub Desktop.

Assignment for Ruby Basics

Implement the calculate_total method so that the tests pass. The method should accept an order represented as an Array of Hashes and calculate the total cost of the order. Each Hash should represent a line item of the order with a key for the quantity and a key for the unit price of the item. After calculating the total of the order and additional tax rate of 5% should be added. The return value should be a string, the total formatted as a price with 2 decimal points and a dollar sign, such as $1.99.

Hints

  • Don't hard code the tax rate as a magic number. If you aren't sure how to avoid that, refer to this slide on when to use constants

  • Make sure you know how to create an Array of Hashes first. If you are not sure, re-read the slides on Arrays and Hashes

  • Not sure how to format a float as a dollar amount? Re-read the slide on string formatting

Extra Credit

  1. To call the calculate_total method with no line items, you have to pass in an empty array. Can you make it so that if can work with no argument at all?

  2. To call the calculate_total method with multiple line items, you have to pass in an array of hashes. Can you make it so that it will work with each Hash as an argument to the method?

  3. Read about RSpec. Convert the Minitest tests in to RSpec specs.

require 'minitest/autorun'
require './calculator'
class CalculatorTest < Minitest::Test
def test_calculate_total_with_empty_order
assert_equal '$0.00', calculate_total([])
end
def test_calculate_total_with_one_line_item
assert_equal '$4.20', calculate_total([
{ quantity: 2, unit_price: 2.0}
])
end
def test_calculate_total_with_two_line_items
assert_equal '$7.00', calculate_total([
{ quantity: 2, unit_price: 2.0},
{ quantity: 3, unit_price: 0.89}
])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment