你的代码工作完美的我:
require 'pp'
class InitializeStore
attr_reader :inventory
def initialize(arr)
@inventory = arr
end
end
class CreateStoreInventory
def initialize(item, value)
@item = item
@value = value
end
end
store_inventories = [
CreateStoreInventory.new('apples', 150),
CreateStoreInventory.new('bananas', 350),
CreateStoreInventory.new('tissue paper', 450),
CreateStoreInventory.new('soap', 850),
]
my_store = InitializeStore.new(store_inventories)
pp my_store.inventory
--output:--
[#<CreateStoreInventory:0x000001008423e8 @item="apples", @value=150>,
#<CreateStoreInventory:0x00000100842398 @item="bananas", @value=350>,
#<CreateStoreInventory:0x00000100842348 @item="tissue paper", @value=450>,
#<CreateStoreInventory:0x00000100842258 @item="soap", @value=850>]
1)哦,但你没有发布您的代码。调试虚构代码很困难。
2)你的班级名称都是错误的。类名不应有动词,例如初始化,创建。类名称是的事情,这是名词,例如:
require 'pp'
class Store
attr_reader :inventory
def initialize(arr)
@inventory = arr
end
end
class Product
def initialize(name, price)
@name = name
@price = price
end
end
products = [
Product.new('apples', 150),
Product.new('bananas', 350),
Product.new('tissue paper', 450),
Product.new('soap', 850),
]
my_store = Store.new(products)
pp my_store.inventory
--output:--
[#<Product:0x00000100842438 @name="apples", @price=150>,
#<Product:0x000001008423e8 @name="bananas", @price=350>,
#<Product:0x00000100842398 @name="tissue paper", @price=450>,
#<Product:0x00000100842348 @name="soap", @price=850>]
3)puts
< - >p
< - >pp
puts arr
:打印出array--的每个元素的字符串表示紧接着换行。如果元素是一个字符串,并且它已经以换行符结束,那么puts不会添加另一个换行符。
p arr
:打印整个数组的字符串表示形式,它看起来像您在代码中指定的数组,例如, [1,2,3],附带引号。
pp arr
:漂亮的印花数组。像p
一样,但添加了一些格式以使输出更易于阅读。
你如何初始化这个'store'变量? – 2014-08-31 16:42:44
'store = ClassName.new()' – user3379926 2014-08-31 16:43:24
您可以发布该课程的相关部分吗? – 2014-08-31 16:44:18