From 621487a0cd8acc5bbec73c98ebbb23c519ba6e6d Mon Sep 17 00:00:00 2001 From: takahashim Date: Mon, 23 Nov 2015 19:51:02 +0900 Subject: add {Array|Hash|String}.try_convert --- mrbgems/mruby-hash-ext/mrblib/hash.rb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'mrbgems/mruby-hash-ext/mrblib') 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 @@ -60,6 +60,25 @@ class Hash h end + ## + # call-seq: + # Hash.try_convert(obj) -> hash or nil + # + # Try to convert obj into a hash, using to_hash method. + # Returns converted hash or nil if obj 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 -- cgit v1.2.3