ruby-changes:25323
From: marcandre <ko1@a...>
Date: Mon, 29 Oct 2012 06:20:06 +0900 (JST)
Subject: [ruby-changes:25323] marcandRe: r37375 (trunk): * lib/ostruct.rb: Also accept {Open}Struct as argument to new
marcandre 2012-10-29 06:19:50 +0900 (Mon, 29 Oct 2012) New Revision: 37375 http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=37375 Log: * lib/ostruct.rb: Also accept {Open}Struct as argument to new [ruby-core:47476] [Feature #7007] Modified files: trunk/NEWS trunk/lib/ostruct.rb trunk/test/ostruct/test_ostruct.rb Index: lib/ostruct.rb =================================================================== --- lib/ostruct.rb (revision 37374) +++ lib/ostruct.rb (revision 37375) @@ -74,7 +74,8 @@ # Creates a new OpenStruct object. By default, the resulting OpenStruct # object will have no attributes. # - # The optional +hash+, if given, will generate attributes and values. + # The optional +hash+, if given, will generate attributes and values + # (can be a Hash, an OpenStruct or a Struct). # For example: # # require 'ostruct' @@ -86,8 +87,9 @@ def initialize(hash=nil) @table = {} if hash - for k,v in hash - @table[k.to_sym] = v + hash.each_pair do |k, v| + k = k.to_sym + @table[k] = v new_ostruct_member(k) end end Index: NEWS =================================================================== --- NEWS (revision 37374) +++ NEWS (revision 37375) @@ -122,6 +122,8 @@ * OpenStruct#eql? * OpenStruct#hash * OpenStruct#to_h converts the struct to a hash. + * extended method: + * OpenStruct.new also accepts an OpenStruct / Struct. * pathname * extended method: Index: test/ostruct/test_ostruct.rb =================================================================== --- test/ostruct/test_ostruct.rb (revision 37374) +++ test/ostruct/test_ostruct.rb (revision 37375) @@ -2,6 +2,13 @@ require 'ostruct' class TC_OpenStruct < Test::Unit::TestCase + def test_initialize + h = {name: "John Smith", age: 70, pension: 300} + assert_equal h, OpenStruct.new(h).to_h + assert_equal h, OpenStruct.new(OpenStruct.new(h)).to_h + assert_equal h, OpenStruct.new(Struct.new(*h.keys).new(*h.values)).to_h + end + def test_equality o1 = OpenStruct.new o2 = OpenStruct.new -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/