ruby-changes:25319
From: marcandre <ko1@a...>
Date: Mon, 29 Oct 2012 06:19:54 +0900 (JST)
Subject: [ruby-changes:25319] marcandRe: r37372 (trunk): * lib/ostruct.rb (each_pair): Add #each_pair [#1400]
marcandre 2012-10-29 06:18:53 +0900 (Mon, 29 Oct 2012) New Revision: 37372 http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=37372 Log: * lib/ostruct.rb (each_pair): Add #each_pair [#1400] Modified files: trunk/NEWS trunk/lib/ostruct.rb trunk/test/ostruct/test_ostruct.rb Index: lib/ostruct.rb =================================================================== --- lib/ostruct.rb (revision 37371) +++ lib/ostruct.rb (revision 37372) @@ -114,6 +114,20 @@ end # + # Yields all attributes (as a symbol) along with the corresponding values + # or returns an enumerator if not block is given. + # Example: + # + # require 'ostruct' + # data = OpenStruct.new("country" => "Australia", :population => 20_000_000) + # data.each_pair.to_a # => [[:country, "Australia"], [:population, 20000000]] + # + def each_pair + return to_enum __method__ unless block_given? + @table.each_pair{|p| yield p} + end + + # # Provides marshalling support for use by the Marshal library. # def marshal_dump Index: NEWS =================================================================== --- NEWS (revision 37371) +++ NEWS (revision 37372) @@ -118,6 +118,7 @@ * ostruct * new methods: + * OpenStruct#each_pair * OpenStruct#to_h converts the struct to a hash. * pathname Index: test/ostruct/test_ostruct.rb =================================================================== --- test/ostruct/test_ostruct.rb (revision 37371) +++ test/ostruct/test_ostruct.rb (revision 37372) @@ -85,4 +85,11 @@ assert_equal(h, OpenStruct.new("name" => "John Smith", "age" => 70, pension: 300).to_h) end + + def test_each_pair + h = {name: "John Smith", age: 70, pension: 300} + os = OpenStruct.new(h) + assert_equal '#<Enumerator: #<OpenStruct name="John Smith", age=70, pension=300>:each_pair>', os.each_pair.inspect + assert_equal [[:name, "John Smith"], [:age, 70], [:pension, 300]], os.each_pair.to_a + end end -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/