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
- "何时在 Ruby 中使用 Struct 而不是 Hash?" 也有一些非常好的点(与哈希的使用相比).
- 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).