1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

OpenStruct#dig

* lib/ostruct.rb (dig): Implement OpenStruct#dig
  [Feature #11688]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@52611 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2015-11-17 05:36:03 +00:00
parent 66e2139b1a
commit 482530680c
3 changed files with 34 additions and 0 deletions

View file

@ -1,3 +1,8 @@
Tue Nov 17 14:36:00 2015 Kenichi Kamiya <kachick1@gmail.com>
* lib/ostruct.rb (dig): Implement OpenStruct#dig
[Feature #11688]
Tue Nov 17 14:04:14 2015 NAKAMURA Usaku <usa@ruby-lang.org>
* ext/socket/lib/socket.rb (Socket#recvmsg{,_nonblock}): default values

View file

@ -214,6 +214,24 @@ class OpenStruct
modifiable[new_ostruct_member(name)] = value
end
#
# Retrieves the value object corresponding to the each +name+
# objects repeatedly.
#
# address = OpenStruct.new('city' => "Anytown NC", 'zip' => 12345)
# person = OpenStruct.new('name' => 'John Smith', 'address' => address)
# person.dig(:address, 'zip') # => 12345
# person.dig(:business_address, 'zip') # => nil
#
def dig(name, *names)
begin
name = name.to_sym
rescue NoMethodError
return
end
@table.dig(name, *names)
end
#
# Remove the named field from the object. Returns the value that the field
# contained if it was defined.

View file

@ -108,6 +108,17 @@ class TC_OpenStruct < Test::Unit::TestCase
assert_equal :bar, os['foo']
end
def test_dig
os1 = OpenStruct.new
os2 = OpenStruct.new
os1.child = os2
os2.foo = :bar
os2.child = [42]
assert_equal :bar, os1.dig("child", :foo)
assert_nil os1.dig("parent", :foo)
assert_nil os1.dig("child", 0)
end
def test_to_h
h = {name: "John Smith", age: 70, pension: 300}
os = OpenStruct.new(h)