这里的这个属性如何在ruby类中拥有多个属性? [英] How this one attribute here hold multiple attribute in ruby class?

查看:86
本文介绍了这里的这个属性如何在ruby类中拥有多个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,这里有一个称为属性"的属性,我们在类中对其进行了初始化,所以问题是名称和衬衫属性来自何处,因为我们没有在类中对其进行初始化和定义?

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?

推荐答案

在Ruby中,如果定义正确,则最后一个参数将自动解释为哈希,并且您可以在不使用{}的情况下传递该哈希.由于只有一个参数,因此它也被视为最后一个参数:

In 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:

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

与以下相同:

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

这篇关于这里的这个属性如何在ruby类中拥有多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆