aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--NEWS2
-rw-r--r--lib/ostruct.rb8
-rw-r--r--test/ostruct/test_ostruct.rb7
3 files changed, 14 insertions, 3 deletions
diff --git a/NEWS b/NEWS
index beda22536b..3c2040fee4 100644
--- a/NEWS
+++ b/NEWS
@@ -122,6 +122,8 @@ with all sufficient information, see the ChangeLog file.
* 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:
diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index 8fc3de6e72..17b3ab05e2 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -74,7 +74,8 @@ class OpenStruct
# 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 @@ class OpenStruct
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
diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb
index a7cfbe994f..491f950838 100644
--- a/test/ostruct/test_ostruct.rb
+++ b/test/ostruct/test_ostruct.rb
@@ -2,6 +2,13 @@ require 'test/unit'
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