зеркало из https://github.com/github/ruby.git
* 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:
Родитель
22115ec87e
Коммит
3785d2675a
2
NEWS
2
NEWS
|
@ -122,6 +122,8 @@ with all sufficient information, see the ChangeLog file.
|
||||||
* OpenStruct#eql?
|
* OpenStruct#eql?
|
||||||
* OpenStruct#hash
|
* OpenStruct#hash
|
||||||
* OpenStruct#to_h converts the struct to a hash.
|
* OpenStruct#to_h converts the struct to a hash.
|
||||||
|
* extended method:
|
||||||
|
* OpenStruct.new also accepts an OpenStruct / Struct.
|
||||||
|
|
||||||
* pathname
|
* pathname
|
||||||
* extended method:
|
* extended method:
|
||||||
|
|
|
@ -74,7 +74,8 @@ class OpenStruct
|
||||||
# Creates a new OpenStruct object. By default, the resulting OpenStruct
|
# Creates a new OpenStruct object. By default, the resulting OpenStruct
|
||||||
# object will have no attributes.
|
# 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:
|
# For example:
|
||||||
#
|
#
|
||||||
# require 'ostruct'
|
# require 'ostruct'
|
||||||
|
@ -86,8 +87,9 @@ class OpenStruct
|
||||||
def initialize(hash=nil)
|
def initialize(hash=nil)
|
||||||
@table = {}
|
@table = {}
|
||||||
if hash
|
if hash
|
||||||
for k,v in hash
|
hash.each_pair do |k, v|
|
||||||
@table[k.to_sym] = v
|
k = k.to_sym
|
||||||
|
@table[k] = v
|
||||||
new_ostruct_member(k)
|
new_ostruct_member(k)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -2,6 +2,13 @@ require 'test/unit'
|
||||||
require 'ostruct'
|
require 'ostruct'
|
||||||
|
|
||||||
class TC_OpenStruct < Test::Unit::TestCase
|
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
|
def test_equality
|
||||||
o1 = OpenStruct.new
|
o1 = OpenStruct.new
|
||||||
o2 = OpenStruct.new
|
o2 = OpenStruct.new
|
||||||
|
|
Загрузка…
Ссылка в новой задаче