How does this attribute here contain multiple attributes in a ruby ​​class?

Here, as you can see, we have one attribute called "attributes" and we initialize it in our class, so the question is, where do the name and shirt attributes come from since we don't 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 check this instance of the shirt class I get a hash:

@attributes={:name=>"go", :size=>"42"}

      

Can anyone explain this?

+1


source to share


3 answers


In Ruby, if defined correctly, the last argument is automatically interpreted as a hash and you can pass it without {}

. Since there is only one argument, it also counts as the last argument:

store = Shirt.new(name: "go", size: "42")
#=> #<Shirt:0x000000022275c0 @attribute={:name=>"go", :size=>"42"}>

      



matches:

store = Shirt.new({name: "go", size: "42"})
#=> #<Shirt:0x000000022271d8 @attribute={:name=>"go", :size=>"42"}>

      

+1


source


@attributes={:name=>"go", :size=>"42"}

      

This line tells you that you have one instance variable named @attributes

and its value is a hash,{:name=>"go", :size=>"42"}



See the difference with two simple variables instead

class A
  def initialize(dogs, cats)
    @dogs = dogs
    @cats = cats
  end
end

A.new(4, 5)
 => #<A:0x007f96830e3c80 @dogs=4, @cats=5> 

      

0


source


directive attr_accessor :attribute

defines 2 methods

def attribute; @attribute;end

and

def attribute=(value); @attribute=value;end

but as you type, store = Shirt.new(name: "go", size: "42")

you define a hash and pass it to the s attribute :

init_values={name: "go", size: "42"}
store = Shirt.new(init_values)

      

in initialization methods, attributes

param is treated as a hash and passed to the @attribute s instance variable

try to check

store = Shirt.new(["go","42"])
store = Shirt.new({})

      

ps.

try with attr_accessor :attributes

and then you can use

store.attributes
store.attributes=

      

0


source







All Articles