class OpenStruct
For all these reasons, consider not using OpenStruct at all.
ending with !
.
Note that a subclass’ methods may not be overwritten, nor can OpenStruct’s own methods
It is recommended (but not enforced) to not use fields ending in !
;
o.class! # => OpenStruct
o.class # => :luxury
o = OpenStruct.new(make: ‘Bentley’, class: :luxury)
and defines aliases for builtin public methods by adding a !
:
To help remedy clashes, OpenStruct uses only protected/private methods ending with !
o.methods # => [:foo, :bar]
o.methods = [:foo, :bar]
o.methods # => [:to_h, :marshal_load, :marshal_dump, :each_pair, …
o = OpenStruct.new
or security issues:
Builtin methods may be overwritten this way, which may be a source of bugs
o.then # => nil in Ruby < 2.6, enumerator for Ruby >= 2.6
o = OpenStruct.new
This may also be the source of incompatibilities between Ruby versions:
since the keys create methods and names of methods are never garbage collected.
(e.g. JSON web request) may be susceptible to a “symbol denial of service” attack
This is a potential security issue; building OpenStruct from untrusted user data
entries can be 200 times slower than accessing the hash directly.
Creating an open struct from a small Hash and accessing a few of the
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
== Caveats
Ractor compatibility: A frozen OpenStruct with shareable values is itself shareable.
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[:“length (in inches)”] # => 24
measurements = OpenStruct.new(“length (in inches)” => 24)
still be reached through the Object#send method or using [].
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, or +nil+ if there is no such 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) name = name.to_sym new_ostruct_member!(name) @table[name] = value end
def delete_field(name, &block)
person.delete_field('number') { 8675_309 } # => 8675309
person.delete_field('number') # => NameError
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"
or a NameError is raised if no block was given.
If the field is not defined, the result of the block is returned,
contained if it was defined. You may optionally provide a block.
Removes the named field from the object and returns the value the field
def delete_field(name, &block) sym = name.to_sym begin singleton_class.remove_method(sym, "#{sym}=") rescue NameError end @table.delete(sym) do return yield if block raise! NameError.new("no field '#{sym}' in #{self}", sym) end end
def dig(name, *names)
person.dig(:address, "zip") # => 12345
person = OpenStruct.new("name" => "John Smith", "address" => address)
address = OpenStruct.new("city" => "Anytown NC", "zip" => 12345)
require "ostruct"
Examples:
See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
The nested objects may be instances of various classes.
that is specified by +name+ and +identifiers+.
Finds and returns the object in nested objects
ostruct.dig(name, *identifiers) -> 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 defined?(yield) @table.each_pair{|p| yield p} self end
def encode_with(coder) # :nodoc:
Provides marshalling support for use by the YAML library.
def encode_with(coder) # :nodoc: @table.each_pair do |key, value| coder[key.to_s] = value end if @table.size == 1 && @table.key?(:table) # support for legacy format # in the very unlikely case of a single entry called 'table' coder['legacy_support!'] = true # add a bogus second entry end 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.freeze super end
def hash # :nodoc:
Computes a hash code for this OpenStruct.
def hash # :nodoc: @table.hash end
def init_with(coder) # :nodoc:
Provides marshalling support for use by the YAML library.
def init_with(coder) # :nodoc: h = coder.map if h.size == 1 # support for legacy format key, val = h.first if key == 'table' h = val end end update_to_values!(h) 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) if HAS_PERFORMANCE_WARNINGS && Warning[:performance] warn "OpenStruct use is discouraged for performance reasons", uplevel: 1, category: :performance end if hash update_to_values!(hash) else @table = {} end end
def initialize_clone(orig) # :nodoc:
Duplicates an OpenStruct object's Hash table.
def initialize_clone(orig) # :nodoc: # clones the singleton class for us = @table.dup unless @table.frozen?
def initialize_dup(orig) # :nodoc:
def initialize_dup(orig) # :nodoc: _to_values!(@table)
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 is_method_protected!(name) # :nodoc:
def is_method_protected!(name) # :nodoc: spond_to?(name, true) e name.match?(/!$/) r = method!(name).owner wner.class == ::Class ner < ::OpenStruct lf.class!.ancestors.any? do |mod| return false if mod == ::OpenStruct mod == owner d
def marshal_dump # :nodoc:
Provides marshalling support for use by the Marshal library.
def marshal_dump # :nodoc: @table end
def method_missing(mid, *args) # :nodoc:
def method_missing(mid, *args) # :nodoc: args.length me = mid[/.*(?==\z)/m] en != 1 ise! ArgumentError, "wrong number of arguments (given #{len}, expected 1)", caller(1) ostruct_member_value!(mname, args[0]) len == 0 le[mid] n per ue NoMethodError => err r.backtrace.shift ise!
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: unless @table.key?(name) || is_method_protected!(name) if defined?(::Ractor) getter_proc = nil.instance_eval{ Proc.new { @table[name] } } setter_proc = nil.instance_eval{ Proc.new {|x| @table[name] = x} } ::Ractor.make_shareable(getter_proc) ::Ractor.make_shareable(setter_proc) else getter_proc = Proc.new { @table[name] } setter_proc = Proc.new {|x| @table[name] = x} end define_singleton_method!(name, &getter_proc) define_singleton_method!("#{name}=", &setter_proc) end end
def to_h(&block)
# => {"country" => "AUSTRALIA", "capital" => "CANBERRA" }
data.to_h {|name, value| [name.to_s, value.upcase] }
data.to_h # => {:country => "Australia", :capital => "Canberra" }
data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
require "ostruct"
the receiver will be used as pairs.
If a block is given, the results of the block on each pair of
each attribute (as symbols) and their corresponding values.
Converts the OpenStruct to a hash with keys representing
ostruct.to_h {|name, value| block } -> hash
ostruct.to_h -> hash
call-seq:
def to_h(&block) if block @table.to_h(&block) else @table.dup end end
def to_h(&block)
def to_h(&block) if block @table.map(&block).to_h else @table.dup end end
def update_to_values!(hash) # :nodoc:
def update_to_values!(hash) # :nodoc: = {} ach_pair do |k, v| ostruct_member_value!(k, v)