加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby类vs Struct

发布时间:2020-12-16 20:03:05 所属栏目:百科 来源:网络整理
导读:我已经看到使用Structs的代码库来包装一个类中的属性和行为. Ruby Class和Struct之间有什么区别?何时应该使用另一个? 解决方法 从 Struct docs: A Struct is a convenient way to bundle a number of attributes together,using accessor methods,without
我已经看到使用Structs的代码库来包装一个类中的属性和行为.
Ruby Class和Struct之间有什么区别?何时应该使用另一个?

解决方法

从 Struct docs:

A Struct is a convenient way to bundle a number of attributes together,using accessor methods,without having to write an explicit class.

The Struct class generates new subclasses that hold a set of members and their values. For each member a reader and writer method is created similar to Module#attr_accessor.

所以,如果我想要一个Person类,我可以访问一个name属性(读写),我可以通过声明一个类:

class Person
  attr_accessor :name

  def initalize(name)
    @name = name
  end
end

或使用Struct

Person = Struct.new(:name)

在这两种情况下,我可以运行以下代码:

person = Person.new
 person.name = "Name"
 #or Person.new("Name")
 puts person.name

使用时?

如描述所述,当我们需要一组可访问的属性而不必编写一个显式类时,我们使用Structs.

例如,我想要一个点变量来保存X和Y值:

point = Struct.new(:x,:y).new(20,30)
point.x #=> 20

更多的例子:

> http://blog.steveklabnik.com/posts/2012-09-01-random-ruby-tricks–struct-new
>“When to use Struct instead of Hash in Ruby?”也有一些很好的点(与使用哈希比较).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读