【问题标题】:Questions about arrays in ruby关于ruby中数组的问题
【发布时间】:2013-10-05 14:45:11
【问题描述】:

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

在另一个名为Shop 的类(包括Product 类)中,我使用一个空数组进行初始化。然后使用方法pushproduct 添加到该数组中。

问题发生在Shop类中的方法to_s

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

如果我在不使用Array 的情况下创建Product,我可以访问属性 - 我猜问题出在Array...

【问题讨论】:

  • 首先向我们展示您创建的课程,然后向我们提出问题,指出您遇到的困惑..
  • 代码中的endeach块的结尾还是def to_s块的结尾?
  • 无论是谁编辑了它,您可能已经更改了 OP 的问题。请注意我上面关于不匹配的ends 的评论。 =)

标签: ruby arrays oop


【解决方案1】:

首先,你的方块不匹配。

你想要:

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

【讨论】:

  • 您也可以将 John 的建议替代方案写为:def to_s() "Products in the shop:\n" + @list.map(&amp;:name).join("\n") end
  • def to_s() 后面不需要冒号吗?此外,括号是可选的。 =)
  • 如果删除括号,则需要在to_s 之后插入一个;,在end 之前插入另一个。两者都有效。
【解决方案2】:

@list 中的每个元素都作为list 生成给each 块。

假设 @list 是一个带有 Product 对象的 Enumerable,您应该可以通过 list.name 获取块内的 name 属性。

【讨论】:

    【解决方案3】:

    我更喜欢mapjoin 而不是each&lt;&lt;(只是一个偏好),以及大括号({})而不是do end,因为我喜欢暗示返回值很重要使用大括号,do end 块用于副作用,例如

    def to_s
      "Products in the shop:\n" << @list.map{|item| item.name}.join("\n")
    end
    

    我也不会使用puts,因为to_s 应该返回一个字符串,而不是输出一个字符串。

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2013-10-03
      • 2011-03-04
      相关资源
      最近更新 更多