2014-08-31 26 views
-2

数组我曾在一个名为store为什么我得到4回来时,我应该得到的红宝石

#<InitializeStore:0x007f83a39b72a0 
@inventory=[ 
    #<CreateStoreInventory:0x007f83a39b7228 @item="apples", @value=150>, 
    #<CreateStoreInventory:0x007f83a39b71d8 @item="bananas", @value=350>, 
    #<CreateStoreInventory:0x007f83a39b7188 @item="tissue paper", @value=450>, 
    #<CreateStoreInventory:0x007f83a39b7138 @item="soap", @value=850> 
]> 

现在,当我尝试做变量如下:store.inventory我应该得到的数组。相反,我得到阵列内的所有东西吐出4次。这不是我想要的。我希望能够做到store.inventory并获得对象数组。

我想分配store.inventory到库存数组,但它已经是一个数组...

想法?

+0

你如何初始化这个'store'变量? – 2014-08-31 16:42:44

+0

'store = ClassName.new()' – user3379926 2014-08-31 16:43:24

+0

您可以发布该课程的相关部分吗? – 2014-08-31 16:44:18

回答

0

这取决于你的InitializeStore是如何实现的。

store.inventory实际上是store.inventory()。这不是字段访问,它是一个方法调用。

其结果取决于该方法(inventory)的实施。

0

你的代码工作完美的我:

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一样,但添加了一些格式以使输出更易于阅读。