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

* lib/ostruct.rb: Also accept {Open}Struct as argument to new

[ruby-core:47476] [Feature #7007]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@37375 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
marcandre 2012-10-28 21:19:50 +00:00
parent 22115ec87e
commit 3785d2675a
3 changed files with 14 additions and 3 deletions

2
NEWS
View file

@ -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:

View file

@ -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

View file

@ -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