我创建了一个类并添加了如下对象:
class Tops
def initialize(neckline, brand, maincolour, style)
@neckline = neckline
@brand = brand
@maincolour = maincolour
@style = style
end
end
top1 = Tops.new("Sweetheart", "Miss Selfridge", "Blue", "Bardot")
top2 = Tops.new("Scoop", "Target", "Pink", "Vest")
top3 = Tops.new("Boat", "Unknown", "Red", "Tank")
然后我使用push
方法将其中一些对象添加到空数组中。
currentTopChoices = []
currentTopChoices.push(top1,top3)
然后我使用了一些each
方法来运行代码块或此数组中的每个对象
currentTopChoices.each { |x| puts @neckline }
所以我的目标是获得数组中对象的每个领口的输出,但我得到一个输出:
Boat
Boat
当我真的想要的时候:
Sweetheart
Boat
这是最后一个物体的领口,但打印了两次。我没有收到任何错误消息,所以我到底错过了什么?
答案 0 :(得分:1)
如果您不介意将attr_accessor
添加到Tops
(这将提供Top#neckline
访问方法),您可以使用Array#map
或(别名) Array#collect
)构建necklines
:
class Tops
attr_accessor :neckline
def initialize(neckline, brand, maincolour, style)
@neckline = neckline
@brand = brand
@maincolour = maincolour
@style = style
end
end
top1 = Tops.new("Sweetheart", "Miss Selfridge", "Blue", "Bardot")
top2 = Tops.new("Scoop", "Target", "Pink", "Vest")
top3 = Tops.new("Boat", "Unknown", "Red", "Tank")
[top1, top3].map(&:neckline) # => ["Sweetheart", "Boat"]
# or, more explicitly
[top1, top3].map { |top| top.neckline } # => ["Sweetheart", "Boat"]
答案 1 :(得分:1)
问题是,不管你是不是在显示你的所有代码,或者在irb中运行这个代码你都会让你自己感到困惑,在某些时候你有一个类似的声明?
@neckline = "Boat"
例如,您发布的代码,如果直接放在 file_name.rb 中,就像这样:
class Tops
def initialize(neckline, brand, maincolour, style)
@neckline = neckline
@brand = brand
@maincolour = maincolour
@style = style
end
end
top1 = Tops.new("Sweetheart", "Miss Selfridge", "Blue", "Bardot")
top2 = Tops.new("Scoop", "Target", "Pink", "Vest")
top3 = Tops.new("Boat", "Unknown", "Red", "Tank")
currentTopChoices = []
currentTopChoices.push(top1,top3)
currentTopChoices.each { |x| puts @neckline }
然后使用ruby file_name.rb
运行只生成2个空行,因为@neckline
未在此范围内定义(顶层),因此它的值为nil
为了让您按照预期的方式工作,您可以添加
attr_reader :neckline
然后引用您传递给每个x.neckline
的广告块中的x
,因为Tops
将获取currentTopChoices
注意:attr_reader
为领口添加了setter和getter,如果你只需要对该属性的读访问权限,那么你应该允许的只是{{1} }),如果真的需要在创建实例后获得并设置实际颈线的值,那么att_accessor
就会有意义。
以下是代码的更新版本,其行为应符合您的预期。
class Tops
attr_reader :neckline # added to allow read access to @neckline
def initialize(neckline, brand, maincolour, style)
@neckline = neckline
@brand = brand
@maincolour = maincolour
@style = style
end
end
top1 = Tops.new("Sweetheart", "Miss Selfridge", "Blue", "Bardot")
top2 = Tops.new("Scoop", "Target", "Pink", "Vest")
top3 = Tops.new("Boat", "Unknown", "Red", "Tank")
currentTopChoices = []
currentTopChoices.push(top1,top3)
currentTopChoices.each { |x| puts x.neckline } # access the neckline property for each element