summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext/mrblib/hash.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2015-11-26 01:02:38 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2015-11-26 01:02:38 +0900
commit2fb12bd90e537e954188e4a4a2d7dac699acabaf (patch)
tree7c28981ea380b3fa0f1bc7f9e59f98e7b2a0cb2d /mrbgems/mruby-hash-ext/mrblib/hash.rb
parent625a3fee7729a12b0ff613e80b7b45ba0e2f086b (diff)
parent621487a0cd8acc5bbec73c98ebbb23c519ba6e6d (diff)
downloadmruby-2fb12bd90e537e954188e4a4a2d7dac699acabaf.tar.gz
mruby-2fb12bd90e537e954188e4a4a2d7dac699acabaf.zip
Merge pull request #3034 from takahashim/try_convert
add {Array|Hash|String}.try_convert
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib/hash.rb')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb19
1 files changed, 19 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
#