[前][次][番号順一覧][スレッド一覧]

ruby-changes:40530

From: nobu <ko1@a...>
Date: Tue, 17 Nov 2015 14:36:29 +0900 (JST)
Subject: [ruby-changes:40530] nobu:r52611 (trunk): OpenStruct#dig

nobu	2015-11-17 14:36:03 +0900 (Tue, 17 Nov 2015)

  New Revision: 52611

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=52611

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

  Modified files:
    trunk/ChangeLog
    trunk/lib/ostruct.rb
    trunk/test/ostruct/test_ostruct.rb
Index: ChangeLog
===================================================================
--- ChangeLog	(revision 52610)
+++ ChangeLog	(revision 52611)
@@ -1,3 +1,8 @@ https://github.com/ruby/ruby/blob/trunk/ChangeLog#L1
+Tue Nov 17 14:36:00 2015  Kenichi Kamiya  <kachick1@g...>
+
+	* lib/ostruct.rb (dig): Implement OpenStruct#dig
+	  [Feature #11688]
+
 Tue Nov 17 14:04:14 2015  NAKAMURA Usaku  <usa@r...>
 
 	* ext/socket/lib/socket.rb (Socket#recvmsg{,_nonblock}): default values
Index: lib/ostruct.rb
===================================================================
--- lib/ostruct.rb	(revision 52610)
+++ lib/ostruct.rb	(revision 52611)
@@ -215,6 +215,24 @@ class OpenStruct https://github.com/ruby/ruby/blob/trunk/lib/ostruct.rb#L215
   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.
   #
Index: test/ostruct/test_ostruct.rb
===================================================================
--- test/ostruct/test_ostruct.rb	(revision 52610)
+++ test/ostruct/test_ostruct.rb	(revision 52611)
@@ -108,6 +108,17 @@ class TC_OpenStruct < Test::Unit::TestCa https://github.com/ruby/ruby/blob/trunk/test/ostruct/test_ostruct.rb#L108
     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)

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]