Class

OpenStruct

Inheritance
< Object

OpenStruct allows you to create data objects and set arbitrary attributes. For example:

  require 'ostruct'

  record = OpenStruct.new
  record.name    = "John Smith"
  record.age     = 70
  record.pension = 300

  puts record.name     # -> "John Smith"
  puts record.address  # -> nil

It is like a hash with a different way to access the data. In fact, it is implemented with a hash, and you can initialize it with one.

  hash = { "country" => "Australia", :population => 20_000_000 }
  data = OpenStruct.new(hash)

  p data        # -> <OpenStruct country="Australia" population=20000000>

Methods

Class

Visibility Signature
public new (hash=nil)

Instance

Visibility Signature
public == (other)
public delete_field (name)
public initialize_copy (orig)
public inspect ()
public marshal_dump ()
public marshal_load (x)
public new_ostruct_member (name)
public to_s ()

Class Method Detail

new(hash=nil)

Create a new OpenStruct object. The optional hash, if given, will generate attributes and values. For example.

  require 'ostruct'
  hash = { "country" => "Australia", :population => 20_000_000 }
  data = OpenStruct.new(hash)

  p data        # -> <OpenStruct country="Australia" population=20000000>

By default, the resulting OpenStruct object will have no attributes.

Instance Method Detail

==(other)

Compare this object and other for equality.

delete_field(name)

Remove the named field from the object.

initialize_copy(orig)

Duplicate an OpenStruct object members.

inspect()

Returns a string containing a detailed summary of the keys and values.

marshal_dump()

marshal_load(x)

new_ostruct_member(name)

to_s()

Alias for inspect