summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext
diff options
context:
space:
mode:
authortakahashim <[email protected]>2015-11-23 19:51:02 +0900
committertakahashim <[email protected]>2015-11-24 08:39:39 +0900
commit621487a0cd8acc5bbec73c98ebbb23c519ba6e6d (patch)
tree7c28981ea380b3fa0f1bc7f9e59f98e7b2a0cb2d /mrbgems/mruby-hash-ext
parent625a3fee7729a12b0ff613e80b7b45ba0e2f086b (diff)
downloadmruby-621487a0cd8acc5bbec73c98ebbb23c519ba6e6d.tar.gz
mruby-621487a0cd8acc5bbec73c98ebbb23c519ba6e6d.zip
add {Array|Hash|String}.try_convert
Diffstat (limited to 'mrbgems/mruby-hash-ext')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb19
-rw-r--r--mrbgems/mruby-hash-ext/test/hash.rb6
2 files changed, 25 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index f72cb54e8..2727e1f65 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -62,6 +62,25 @@ class Hash
##
# call-seq:
+ # Hash.try_convert(obj) -> hash or nil
+ #
+ # Try to convert <i>obj</i> into a hash, using to_hash method.
+ # Returns converted hash or nil if <i>obj</i> cannot be converted
+ # for any reason.
+ #
+ # Hash.try_convert({1=>2}) # => {1=>2}
+ # Hash.try_convert("1=>2") # => nil
+ #
+ def self.try_convert(obj)
+ if obj.respond_to?(:to_hash)
+ obj.to_hash
+ else
+ nil
+ end
+ end
+
+ ##
+ # call-seq:
# hsh.merge!(other_hash) -> hsh
# hsh.merge!(other_hash){|key, oldval, newval| block} -> hsh
#
diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb
index 4a2251b6c..8b6b2e5b9 100644
--- a/mrbgems/mruby-hash-ext/test/hash.rb
+++ b/mrbgems/mruby-hash-ext/test/hash.rb
@@ -39,6 +39,12 @@ assert('Hash.[] "c_key", "c_value"') do
end
end
+assert('Hash.try_convert') do
+ assert_nil Hash.try_convert(nil)
+ assert_nil Hash.try_convert("{1=>2}")
+ assert_equal({1=>2}, Hash.try_convert({1=>2}))
+end
+
assert('Hash#merge!') do
a = { 'abc_key' => 'abc_value', 'cba_key' => 'cba_value' }
b = { 'cba_key' => 'XXX', 'xyz_key' => 'xyz_value' }