From: Alex Alex on 25 Feb 2010 10:34 Hello all. I have two classes: class CartItem attr_reader :product, :quantity def initialize(product) @product = product @quantity = 1 end def increment_quantity @quantity += 1 end def title @product.title end def price @product.price * @quantity end end class Cart attr_reader :items def initialize @items = [] end def add_product(product) current_item = @items.find {|item| item.product == product} if current_item current_item.increment_quantity end end end I don't understand, how class Cart can see method "increment_quantity" from class CartItem? -- Posted via http://www.ruby-forum.com/.
From: Nick Brown on 25 Feb 2010 11:09 Alex: Because Ruby is a dynamically-typed language, it doesn't have to "see" the method. At runtime, if current_item happens to be an object with responds to the 'increment_quantity' method, then current_item.increment_quantity will work fine. If the object does not respond to that method, it will raise an error. -- Posted via http://www.ruby-forum.com/.
From: Eric Christopherson on 25 Feb 2010 18:46 On Thu, Feb 25, 2010 at 10:09 AM, Nick Brown <nick(a)nick-brown.com> wrote: > Alex: Because Ruby is a dynamically-typed language, it doesn't have to > "see" the method. At runtime, if current_item happens to be an object > with responds to the 'increment_quantity' method, then > current_item.increment_quantity will work fine. > > If the object does not respond to that method, it will raise an error. And methods are public if not specified otherwise.
From: Alex Alex on 26 Feb 2010 01:18 Nick Brown wrote: > Alex: Because Ruby is a dynamically-typed language, it doesn't have to > "see" the method. At runtime, if current_item happens to be an object > with responds to the 'increment_quantity' method, then > current_item.increment_quantity will work fine. > > If the object does not respond to that method, it will raise an error. Thanks guys -- Posted via http://www.ruby-forum.com/.
From: Alex Alex on 26 Feb 2010 01:21 Nick Brown wrote: > Alex: Because Ruby is a dynamically-typed language, it doesn't have to > "see" the method. At runtime, if current_item happens to be an object > with responds to the 'increment_quantity' method, then > current_item.increment_quantity will work fine. > > If the object does not respond to that method, it will raise an error. And another nuby question: What class have object "current_item"? -- Posted via http://www.ruby-forum.com/.
|
Next
|
Last
Pages: 1 2 Prev: RubyZip help needed Next: Error on iterating through a set of nested tables in a form |