Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
OpenStruct#delete_field
delete_field(name) { || ... }
lib/ostruct.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/lib/ostruct.rb, line 371
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
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