class OpenStruct
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