这个属性如何在ruby类中保存多个属性?

在这里,你看到我们有一个名为“属性”的属性,我们在我们的类中初始化它,所以问题是名称和衬衫属性来自哪里,因为我们不在我们的类中初始化和定义它们?

class Shirt attr_accessor :attribute def initialize(attributes) @attributes = attributes end end store = Shirt.new(name: "go", size: "42") 

当我检查这个衬衫类的实例时,我得到一个哈希:

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

有人可以帮忙解释一下吗?

在Ruby中如果正确定义,最后一个参数会自动解释为哈希,并且允许您在没有{}情况下传递它。 由于只有一个参数,它也被认为是最后一个参数:

 store = Shirt.new(name: "go", size: "42") #=> #"go", :size=>"42"}> 

是相同的:

 store = Shirt.new({name: "go", size: "42"}) #=> #"go", :size=>"42"}> 
 @attributes={:name=>"go", :size=>"42"} 

@attributes对你说的是你有一个名为@attributes实例变量,它的值是一个哈希值, {:name=>"go", :size=>"42"}

用两个简单的变量来区分

 class A def initialize(dogs, cats) @dogs = dogs @cats = cats end end A.new(4, 5) => # 

指令attr_accessor :attribute定义2个方法

def attribute; @attribute;end

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

但是当你输入store = Shirt.new(name: "go", size: "42")你定义一个哈希并将它传递给属性s param:

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

在initialize方法中, attributes param被视为Hash并传递给@attribute 实例变量

试试看

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

PS。

尝试使用attr_accessor :attributes然后你就可以使用了

 store.attributes store.attributes=