问题描述
一般来说,与 Struct 相比,使用 OpenStruct 的优缺点是什么?哪种类型的一般用例适合这些用例?
In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use-cases would fit each of these?
推荐答案
使用 OpenStruct
,您可以任意创建属性.另一方面,Struct
必须在创建时定义其属性.选择其中之一应主要基于您是否需要稍后添加属性.
With an OpenStruct
, you can arbitrarily create attributes. A Struct
, on the other hand, must have its attributes defined when you create it. The choice of one over the other should be based primarily on whether you need to be able to add attributes later.
考虑它们的方式是将它们作为一侧的哈希和另一侧的类之间的范围的中间地带.它们比 Hash
暗示了数据之间更具体的关系,但它们没有类那样的实例方法.例如,函数的一堆选项在散列中有意义;他们只是松散的关系.函数所需的姓名、电子邮件和电话号码可以一起打包在 Struct
或 OpenStruct
中.如果该姓名、电子邮件和电话号码需要以姓氏"和姓氏"格式提供姓名的方法,那么您应该创建一个类来处理它.
The way to think about them is as the middle ground of the spectrum between Hashes on one side and classes on the other. They imply a more concrete relationship amongst the data than does a Hash
, but they don't have the instance methods as would a class. A bunch of options for a function, for example, make sense in a hash; they're only loosely related. A name, email, and phone number needed by a function could be packaged together in a Struct
or OpenStruct
. If that name, email, and phone number needed methods to provide the name in both "First Last" and "Last, First" formats, then you should create a class to handle it.
这篇关于什么时候应该使用 Struct 和 OpenStruct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!