In Ruby, OpenStruct
is a class that allows you to create data structures similar to a hash or a struct, but with the ability to access and set values using dot notation instead of square brackets.
To use OpenStruct
, you first need to require the ostruct
library:
main.rb18 chars2 lines
Then, you can create an instance of OpenStruct
and set values using dot notation:
main.rb61 chars4 lines
You can also initialize an OpenStruct
object with a hash:
main.rb47 chars2 lines
You can access the values using dot notation:
main.rb62 chars6 lines
OpenStruct
objects are also enumerable, meaning you can iterate over the keys and values:
main.rb144 chars9 lines
OpenStruct
provides a convenient way to create data structures on the fly without defining a formal class. However, if you need more control or functionality, it's generally recommended to create a custom class or struct.
Note: OpenStruct
is part of the Ruby standard library, so you don't need additional gems to use it.
gistlibby LogSnag