class OpenStruct
of these properties compared to using a Hash or a Struct.
the objects that are created, as there is much more overhead in the setting
This should be a consideration if there is a concern about the performance of
method_missing and define_singleton_method.
necessary methods for properties. This is accomplished through the methods
An OpenStruct utilizes Ruby’s method lookup structure to find and define the
== Implementation
first_pet == second_pet # => true
first_pet # => #<OpenStruct name=“Rowdy”>
first_pet.delete_field(:owner)
first_pet == second_pet # => false
first_pet # => #<OpenStruct name=“Rowdy”, owner=nil>
first_pet.owner = nil
second_pet = OpenStruct.new(:name => “Rowdy”)
first_pet = OpenStruct.new(:name => “Rowdy”, :owner => “John Smith”)
remove the attribute.
delete_field method as setting the property value to nil
will not
Removing the presence of an attribute requires the execution of the
message.queued? # => false
message.send(“queued?=”, false)
message.queued? # => true
message = OpenStruct.new(:queued? => true)
measurements.send(“length (in inches)”) # => 24
measurements = OpenStruct.new(“length (in inches)” => 24)
still be reached through the Object#send method.
on the OpenStruct object as a method for retrieval or assignment, but can
method calls (e.g. ()[]*
) will not be immediately available
Hash keys with spaces or characters that could normally not be used for
# => #<OpenStruct country=“Australia”, capital=“Canberra”>
australia = OpenStruct.new(:country => “Australia”, :capital => “Canberra”)
and can even be initialized with one:
An OpenStruct employs a Hash internally to store the attributes and values
person.address # => nil
person.age # => 70
person.name # => “John Smith”
person.age = 70
person.name = “John Smith”
person = OpenStruct.new
require “ostruct”
== Examples
itself.
accomplished by using Ruby’s metaprogramming to define methods on the class
definition of arbitrary attributes with their accompanying values. This is
An OpenStruct is a data structure, similar to a Hash, that allows the
def ==(other)
first_pet == third_pet # => false
first_pet == second_pet # => true
third_pet = OpenStruct.new("name" => "Rowdy", :age => nil)
second_pet = OpenStruct.new(:name => "Rowdy")
first_pet = OpenStruct.new("name" => "Rowdy")
require "ostruct"
equal.
+other+ when +other+ is an OpenStruct and the two objects' Hash tables are
Compares this object and +other+ for equality. An OpenStruct is equal to
def ==(other) return false unless other.kind_of?(OpenStruct) @table == other.table! end
def [](name)
person[:age] # => 70, same as person.age
person = OpenStruct.new("name" => "John Smith", "age" => 70)
require "ostruct"
Returns the value of an attribute.
ostruct[name] -> object
:call-seq:
def [](name) @table[name.to_sym] end
def []=(name, value)
person.age # => 42
person[:age] = 42 # equivalent to person.age = 42
person = OpenStruct.new("name" => "John Smith", "age" => 70)
require "ostruct"
Sets the value of an attribute.
ostruct[name] = obj -> obj
:call-seq:
def []=(name, value) modifiable?[new_ostruct_member!(name)] = value end
def delete_field(name)
person # => #
person.pension = nil
Setting the value to +nil+ will not remove the attribute:
person # => #
person.delete_field("age") # => 70
person = OpenStruct.new(name: "John", age: 70, pension: 300)
require "ostruct"
contained if it was defined.
Removes the named field from the object. Returns the value that the field
def delete_field(name) sym = name.to_sym begin singleton_class.remove_method(sym, "#{sym}=") rescue NameError end @table.delete(sym) do raise NameError.new("no field `#{sym}' in #{self}", sym) end end
def dig(name, *names)
data.dig(:array, 0, 0) # TypeError: Integer does not have #dig method
data.dig(:array, 1, 0) # => 2
data = OpenStruct.new(:array => [1, [2, 3]])
person.dig(:business_address, "zip") # => nil
person.dig(:address, "zip") # => 12345
person = OpenStruct.new("name" => "John Smith", "address" => address)
address = OpenStruct.new("city" => "Anytown NC", "zip" => 12345)
require "ostruct"
intermediate step is +nil+.
objects by calling +dig+ at each step, returning +nil+ if any
Extracts the nested value specified by the sequence of +name+
ostruct.dig(name, ...) -> object
:call-seq:
def dig(name, *names) begin name = name.to_sym rescue NoMethodError raise TypeError, "#{name} is not a symbol nor a string" end @table.dig(name, *names) end
def each_pair
data.each_pair.to_a # => [[:country, "Australia"], [:capital, "Canberra"]]
data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
require "ostruct"
or returns an enumerator if no block is given.
Yields all attributes (as symbols) along with the corresponding values
ostruct.each_pair -> Enumerator
ostruct.each_pair {|name, value| block } -> ostruct
:call-seq:
def each_pair return to_enum(__method__) { @table.size } unless block_given? @table.each_pair{|p| yield p} self end
def eql?(other)
eql?.
+other+ when +other+ is an OpenStruct and the two objects' Hash tables are
Compares this object and +other+ for equality. An OpenStruct is eql? to
def eql?(other) return false unless other.kind_of?(OpenStruct) @table.eql?(other.table!) end
def freeze
def freeze @table.each_key {|key| new_ostruct_member!(key)} super end
def hash
(and will compare using #eql?).
Two OpenStruct objects with the same content will have the same hash code
Computes a hash code for this OpenStruct.
def hash @table.hash end
def initialize(hash=nil)
data # => #
data = OpenStruct.new(hash)
hash = { "country" => "Australia", :capital => "Canberra" }
require "ostruct"
For example:
(can be a Hash, an OpenStruct or a Struct).
The optional +hash+, if given, will generate attributes and values
object will have no attributes.
Creates a new OpenStruct object. By default, the resulting OpenStruct
def initialize(hash=nil) @table = {} if hash hash.each_pair do |k, v| k = k.to_sym @table[k] = v end end end
def initialize_copy(orig) # :nodoc:
Duplicates an OpenStruct object's Hash table.
def initialize_copy(orig) # :nodoc: super @table = @table.dup end
def inspect
Returns a string containing a detailed summary of the keys and values.
def inspect ids = (Thread.current[InspectKey] ||= []) if ids.include?(object_id) detail = ' ...' else ids << object_id begin detail = @table.map do |key, value| " #{key}=#{value.inspect}" end.join(',') ensure ids.pop end end ['#<', self.class, detail, '>'].join end
def marshal_dump
Provides marshalling support for use by the Marshal library.
def marshal_dump @table end
def marshal_load(x)
Provides marshalling support for use by the Marshal library.
def marshal_load(x) @table = x end
def method_missing(mid, *args) # :nodoc:
def method_missing(mid, *args) # :nodoc: len = args.length if mname = mid[/.*(?==\z)/m] if len != 1 raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1) end modifiable?[new_ostruct_member!(mname)] = args[0] elsif len == 0 # and /\A[a-z_]\w*\z/ =~ mid # if @table.key?(mid) new_ostruct_member!(mid) unless frozen? @table[mid] end else begin super rescue NoMethodError => err err.backtrace.shift raise end end end
def modifiable? # :nodoc:
modified before granting access to the internal Hash table to be modified.
Used internally to check if the OpenStruct is able to be
def modifiable? # :nodoc: begin @modifiable = true rescue exception_class = defined?(FrozenError) ? FrozenError : RuntimeError raise exception_class, "can't modify frozen #{self.class}", caller(3) end @table end
def new_ostruct_member!(name) # :nodoc:
define_singleton_method for both the getter method and the setter method.
OpenStruct. It does this by using the metaprogramming function
Used internally to defined properties on the
def new_ostruct_member!(name) # :nodoc: name = name.to_sym unless singleton_class.method_defined?(name) define_singleton_method(name) { @table[name] } define_singleton_method("#{name}=") {|x| modifiable?[name] = x} end name end
def respond_to_missing?(mid, include_private = false) # :nodoc:
def respond_to_missing?(mid, include_private = false) # :nodoc: mname = mid.to_s.chomp("=").to_sym @table&.key?(mname) || super end
def to_h
data.to_h # => {:country => "Australia", :capital => "Canberra" }
data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
require "ostruct"
each attribute (as symbols) and their corresponding values.
Converts the OpenStruct to a hash with keys representing
def to_h @table.dup end