Ruby 类与结构 [英] Ruby Class vs Struct

查看:47
本文介绍了Ruby 类与结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到代码库使用 Structs 来包装类中的属性和行为.Ruby 类和结构体之间有什么区别?什么时候应该使用一个而不是另一个.?

I have seen codebases using Structs to wrap around attributes and behavior inside a class. What is the difference between a Ruby Class and a Struct? And when should one be used over the other.?

推荐答案

来自 结构文档:

Struct 是一种将多个属性捆绑在一起的便捷方式,使用访问器方法,而无需编写显式类.

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

Struct 类生成包含一组成员及其值的新子类.为每个成员创建一个 reader 和 writer 方法,类似于 Module#attr_accessor.

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 类,我可以通过声明一个类来实现:

So, if I want a Person class that I can access a name attribute (read and write), I either do it by declaring a class:

class Person
  attr_accessor :name

  def initalize(name)
    @name = name
  end
end

或使用结构:

Person = Struct.new(:name)

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

In both cases I can run the following code:

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

什么时候用?

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

As the description states we use Structs when we need a group of accessible attributes without having to write an explicit class.

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

For example I want a point variable to hold X and Y values:

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?" also has some very good points (comparing to the use of hash).

这篇关于Ruby 类与结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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