我有一个名为Product
的课程,其中包含name
,price
和count
。
在另一个名为Shop
的类(包括类Product
)中,我用一个空数组初始化。然后使用方法product
向此数组添加push
。
问题发生在to_s
类的方法Shop
:
def to_s
string = "Products in the shop:\n"
@list.each do |list|
#### how can i get access to the attributes of product like @list.name or something like that ? I have tried loads of different methods but i cant get access to my attributes. (the array doesnt recognize the product class)
puts @list.name
end
如果我在不使用Product
的情况下创建Array
,我可以访问这些属性 - 我想这个问题是因为Array
...
答案 0 :(得分:3)
首先,你的积木不匹配。
你想:
def to_s
string = "Products in the shop:\n"
@list.each do |item|
string << item.name + "\n" # not @list.name! @list is an Array. item is an element of your list.
end
string # you could also say: return string
end
当您尝试将其存储在名为puts
的字符串中时,您不希望使用string
,因为它会将其发送到控制台。你也想确保你也退货。
您不必调用阻止参数item
。您可以将其称为list
,但这会令人困惑,因为您有另一个名为@list
的变量,而block参数根本不是列表 - 只是一个项目来自阵列。
请注意,这不是实现此目的的最有效方法。首选方式如下:
def to_s
products_list = @list.map do |item|
item.name
end
"Products in the shop:\n" + products_list.join("\n")
end
答案 1 :(得分:2)
@list
中的每个元素都作为each
传递给list
块。
假设@list
是一个带有Product
个对象的Enumerable,您应该可以list.name
来获取块内的name属性。
答案 2 :(得分:1)
我希望map
和join
优先于each
和<<
(只是首选项),而支持{}
)优于{{1}因为我喜欢通过使用大括号来暗示返回值很重要,并且有do end
块用于副作用,例如
do end
我也不会使用def to_s
"Products in the shop:\n" << @list.map{|item| item.name}.join("\n")
end
因为puts
应该返回一个字符串,而不是输出一个字符串。