解决方法
从
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?”也有一些很好的点(与使用哈希比较).