diff options
author | jfrazx <[email protected]> | 2021-06-14 08:53:20 -0500 |
---|---|---|
committer | GitHub <[email protected]> | 2021-06-14 09:53:20 -0400 |
commit | 931ea7cfbec6d863cd8b48308804323704a2696c (patch) | |
tree | a2585c739c839d5aa86a4488244087d93dd95bb4 /lib/ostruct.rb | |
parent | 90cad6e14745d812f042df61a6455db022be7389 (diff) |
Add fallback block to `OpenStruct#delete_field` (#1409)
Notes
Notes:
Merged-By: marcandre <[email protected]>
Diffstat (limited to 'lib/ostruct.rb')
-rw-r--r-- | lib/ostruct.rb | 11 |
1 files changed, 9 insertions, 2 deletions
diff --git a/lib/ostruct.rb b/lib/ostruct.rb index 1462901d06..b3ff6efff1 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -326,8 +326,10 @@ class OpenStruct end # - # Removes the named field from the object. Returns the value that the field - # contained if it was defined. + # 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. # # require "ostruct" # @@ -341,6 +343,10 @@ class OpenStruct # person.pension = nil # person # => #<OpenStruct name="John", pension=nil> # + # person.delete_field('number') # => NameError + # + # person.delete_field('number') { 8675_309 } # => 8675309 + # def delete_field(name) sym = name.to_sym begin @@ -348,6 +354,7 @@ class OpenStruct rescue NameError end @table.delete(sym) do + return yield if block_given? raise! NameError.new("no field `#{sym}' in #{self}", sym) end end |