Here as you see we have one attribute called "attributes" and we initialize it in our class, so the question is where the name and shirt attributes come from, as we dont initialize and define them in our class?
class Shirt
attr_accessor :attribute
def initialize(attributes)
@attributes = attributes
end
end
store = Shirt.new(name: "go", size: "42")
Also when I inspect this instance of the shirt class I get a hash:
@attributes={:name=>"go", :size=>"42"}
Anyone can help explain it?
the directive
attr_accessor :attribute
define 2 methodsdef attribute; @attribute;end
and
def attribute=(value); @attribute=value;end
but when you type
store = Shirt.new(name: "go", size: "42")
you are define an hash and pass it to the attributes param:in the initialize methods,
attributes
param is treated as a Hash and passed to the @attributes instance variabletry inspect
ps.
try with
attr_accessor :attributes
and then you will able to useIn Ruby if correctly defined, the last argument is automatically interpreted to be a hash and you are allowed to pass it without the
{}
. Since there is only one argument it too is considered as the last argument:is the same as:
What this line says to you is that you have one instance variable named
@attributes
and its value is an hash,{:name=>"go", :size=>"42"}
Look the difference with two simple variables instead