Skip to content

Instantly share code, notes, and snippets.

@benjamintanweihao
Created October 31, 2013 17:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save benjamintanweihao/7253254 to your computer and use it in GitHub Desktop.
Save benjamintanweihao/7253254 to your computer and use it in GitHub Desktop.
class Order
def initialize
@line_items = []
end
def add_line_item(line_item)
@line_items << line_item
end
def total
subtotals = @line_items.each { |li| li.quantity * li.price }
subtotals.reduce(:+)
end
end
class LineItem
attr_reader :quantity, :price
def initialize(quantity, price)
@price = price
@quantity = quantity
end
end
order = Order.new
order.add_line_item LineItem.new(2, 3.00)
order.add_line_item LineItem.new(4, 1.00)
puts order.total
@marvinsjsu
Copy link

Hi Benjamin,

I'm new to Ruby and still working through the basics. I'm also going through the Pry tutorial on http://www.sitepoint.com/rubyists-time-pry-irb/ ... does the Order object need to have "attr_accessor :line_items" in order for the line_item method to be shown when we do an "ls" when in the Order instance? Below is the output I get without the "attr_accessor" declaration.

marvin-mantes-macbook-pro:7253254 mante$ ruby -r pry order.rb

From: /Users/mante/Documents/App_Academy/Pry/7253254/order.rb @ line 12 Order#total:

10: def total
11:   subtotals = @line_items.each { |li| li.quantity * li.price }

=> 12: binding.pry
13: subtotals.reduce(:+)
14: end

[1] pry(#)> ls
Order#methods: add_line_item total
instance variables: @line_items
locals: _ __ dir ex file in out pry subtotals

@marvinsjsu
Copy link

Btw, thank you for the tutorial ... will be using Pry from here on out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment