Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

OpenStruct#delete_field

delete_field(name) { || ... }

Removes the named field from the object and returns the value the field contained if it was defined. You may optionally provide a block. If the field is not defined, the result of the block is returned, or a NameError is raised if no block was given.

Example
require "ostruct"

person = OpenStruct.new(name: "John", age: 70, pension: 300)

person.delete_field!("age")  # => 70
person                       # => #<OpenStruct name="John", pension=300>

Setting the value to nil will not remove the attribute:

Example
person.pension = nil
person                 # => #<OpenStruct name="John", pension=nil>

person.delete_field('number')  # => NameError

person.delete_field('number') { 8675_309 } # => 8675309
See also #as_json #dig #[]= #each_pair also in 3.4 · 3.2 · 3.1 · 3.0