你的代碼工作完美的我:
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