Inter-class use of variables in ruby -
i'm trying create class instance variables can linked , manipulated separate class. here's code:
class product attr_accessor :name, :quantity def initialize(name, quantity) @name = name @quantity = quantity end end class production def initialize(factory) @factory = factory end def create "#{@name}: #{@factory}" end end
basically, i'd able use attributes instance of product class in production class. if = product.new('widget', 100), want able call a.name variable in instance of production. test have:
a = product.new('widget', 100) b = production.new('building 1') puts b.create('building 1')
however, it's returning following:
: building 1
instead of
widget: building 1
any ideas what's going wrong? i'd add, subtract, etc. quantity. i'm hoping if figure out how link name property can same quantity pretty easily.
first of all, want produce product
during production
, production
must know product
. can example pass product argument create
:
class production def initialize(factory) @factory = factory end def create(product) "#{product.name}: #{@factory}" end end product = product.new('thingy', 123) production = production.new('acme') puts production.create(product) #=> "thingy: acme"
or store in instance variable if need across entire production
class:
class production def initialize(factory, product) @factory = factory @product = product end def create "#{@product.name}: #{@factory}" end end product = product.new('thingy', 123) production = production.new('acme', product) puts production.create #=> "thingy: acme"
Comments
Post a Comment