1 openstruct and struct differences, opestruct you need to create, assign a value directly to the property, and the struct needs to define the attribute before assigning a value to the property. Choose which one to look at when you assign values to a property,
2 structs and Opensturt represent properties that are more closely related than hashes. But they do not have as an instance method of the class, a set of optional functions, if you need to provide a special method for the property, it is best to create a class
3 openstruct can be converted to an object using hash
H = {a:1, b:2}
o = openstruct.new (h)
O.A = 1
O.B = 2
4 structs can quickly define a class
Class MyClass < Struct.new (: A,:B,:C)
End
m = myclass.new
M.A = 1
The following code is the test opensturct and struct speed
Require ' benchmark '
Require ' ostruct '
REP = 100000
User = struct.new (: Name,: Age)
user = "User". Freeze
Age = 21
HASH = {: name = USER,: Age = Age}.freeze
BENCHMARK.BM do |x|
X.report ' openstruct slow ' do
Rep.times do |index|
Openstruct.new (: name = "User",: Age + 21)
End
End
X.report ' openstruct fast ' do
Rep.times do |index|
Openstruct.new (HASH)
End
End
X.report ' Struct slow ' do
Rep.times do |index|
User.new ("User", 21)
End
End
X.report ' Struct fast ' do
Rep.times do |index|
User.new (USER, age)
End
End
End
Opensturt and struct differences