关于ruby中数组的问题

时间:2013-09-29 19:30:48

标签: ruby arrays oop

我有一个名为Product的课程,其中包含namepricecount

在另一个名为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 ...

3 个答案:

答案 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)

我希望mapjoin优先于each<<(只是首选项),而支持{})优于{{1}因为我喜欢通过使用大括号来暗示返回值很重要,并且有do end块用于副作用,例如

do end

我也不会使用def to_s "Products in the shop:\n" << @list.map{|item| item.name}.join("\n") end 因为puts应该返回一个字符串,而不是输出一个字符串。