From 770ddcdfe069f8654a07e0fcc758aea591cdd17d Mon Sep 17 00:00:00 2001 From: nobu Date: Tue, 24 Apr 2012 03:46:55 +0000 Subject: * hash.c, object.c, struct.c, lib/ostruct.rb: add to_h methods. [Feature #6276] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@35452 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- test/ostruct/test_ostruct.rb | 12 ++++++++++++ test/ruby/test_env.rb | 4 ++++ test/ruby/test_hash.rb | 26 +++++++++++++++++++++++++- test/ruby/test_struct.rb | 6 ++++++ 4 files changed, 47 insertions(+), 1 deletion(-) (limited to 'test') diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb index dca2382b2b..1826e40e53 100644 --- a/test/ostruct/test_ostruct.rb +++ b/test/ostruct/test_ostruct.rb @@ -73,4 +73,16 @@ class TC_OpenStruct < Test::Unit::TestCase assert_raise(NoMethodError) { o[:foo] } end + def test_to_h + h = {name: "John Smith", age: 70, pension: 300} + os = OpenStruct.new(h) + to_h = os.to_h + assert_equal(h, to_h) + + to_h[:age] = 71 + assert_equal(70, os.age) + assert_equal(70, h[:age]) + + assert_equal(h, OpenStruct.new("name" => "John Smith", "age" => 70, pension: 300).to_h) + end end diff --git a/test/ruby/test_env.rb b/test/ruby/test_env.rb index 9166f4df6c..8baf762472 100644 --- a/test/ruby/test_env.rb +++ b/test/ruby/test_env.rb @@ -327,6 +327,10 @@ class TestEnv < Test::Unit::TestCase assert_equal(h, ENV.to_hash) end + def test_to_h + assert_equal(ENV.to_hash, ENV.to_h) + end + def test_reject h1 = {} ENV.each_pair {|k, v| h1[k] = v } diff --git a/test/ruby/test_hash.rb b/test/ruby/test_hash.rb index e3c92125c5..0c03bf4726 100644 --- a/test/ruby/test_hash.rb +++ b/test/ruby/test_hash.rb @@ -77,7 +77,7 @@ class TestHash < Test::Unit::TestCase # From rubicon def setup - @cls = Hash + @cls ||= Hash @h = @cls[ 1 => 'one', 2 => 'two', 3 => 'three', self => 'self', true => 'true', nil => 'nil', @@ -631,6 +631,20 @@ class TestHash < Test::Unit::TestCase def test_to_hash h = @h.to_hash assert_equal(@h, h) + assert_instance_of(@cls, h) + end + + def test_to_h + h = @h.to_h + assert_equal(@h, h) + assert_instance_of(Hash, h) + end + + def test_nil_to_h + h = nil.to_h + assert_equal({}, h) + assert_nil(h.default) + assert_nil(h.default_proc) end def test_to_s @@ -932,4 +946,14 @@ class TestHash < Test::Unit::TestCase assert_not_equal(h.hash, h.invert.hash, feature4262) end end + + class TestSubHash < TestHash + class SubHash < Hash + end + + def setup + @cls = SubHash + super + end + end end diff --git a/test/ruby/test_struct.rb b/test/ruby/test_struct.rb index d769e47dc5..b3191902a3 100644 --- a/test/ruby/test_struct.rb +++ b/test/ruby/test_struct.rb @@ -263,4 +263,10 @@ class TestStruct < Test::Unit::TestCase end assert_equal("Insecure: can't modify #{st}::S", error.message, bug5036) end + + def test_to_h + klass = Struct.new(:a, :b, :c, :d, :e, :f) + o = klass.new(1, 2, 3, 4, 5, 6) + assert_equal({a:1, b:2, c:3, d:4, e:5, f:6}, o.to_h) + end end -- cgit v1.2.3