The problem is that somehow you are confusing yourself by either not showing all your code, or maybe running this in irb, where at some point you had a statement like?
@neckline = "Boat"
For example the code you posted, if placed directly in a file_name.rb like so:
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 }
and then run using ruby file_name.rb
would just produce 2 blank lines because @neckline is not define at this scope (toplevel), so it's value is nil
To get this to work the way you intend you can add
attr_reader :neckline
and then refer to x.neckline within the block you pass to each, since x will take one the value of each of the Tops objects in currentTopChoices
note: attr_accessor adds both a setter and a getter for neckline, if you only need read access to that property than that's all you should allow (which is what you get with attr_reader ), if you really need to both get and set the value of neckline on an instance after creating it then att_accessor would make sense.
Here is an updated version of your code that should behave as you are expecting.
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
attr_accessorthen usemapfor the new array.@necklineis un-initialized, it should evaluate toniland thus print two empty lines, notBoat.