what is ostruct in ruby

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.rb
require 'ostruct'
18 chars
2 lines

Then, you can create an instance of OpenStruct and set values using dot notation:

main.rb
person = OpenStruct.new
person.name = "John"
person.age = 30
61 chars
4 lines

You can also initialize an OpenStruct object with a hash:

main.rb
person = OpenStruct.new(name: "John", age: 30)
47 chars
2 lines

You can access the values using dot notation:

main.rb
puts person.name
# Output: John

puts person.age
# Output: 30
62 chars
6 lines

OpenStruct objects are also enumerable, meaning you can iterate over the keys and values:

main.rb
person = OpenStruct.new(name: "John", age: 30)

person.each_pair do |key, value|
  puts "#{key}: #{value}"
end
# Output:
# name: John
# age: 30
144 chars
9 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.

related categories

gistlibby LogSnag