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-array-ext/mrblib/array.rb | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb') diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 35be79339..f19581cdc 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -1,4 +1,29 @@ class Array + ## + # call-seq: + # Array.try_convert(obj) -> array or nil + # + # Tries to convert +obj+ into an array, using +to_ary+ method. + # converted array or +nil+ if +obj+ cannot be converted for any reason. + # This method can be used to check if an argument is an array. + # + # Array.try_convert([1]) #=> [1] + # Array.try_convert("1") #=> nil + # + # if tmp = Array.try_convert(arg) + # # the argument is an array + # elsif tmp = String.try_convert(arg) + # # the argument is a string + # end + # + def self.try_convert(obj) + if obj.respond_to?(:to_ary) + obj.to_ary + else + nil + end + end + ## # call-seq: # ary.uniq! -> ary or nil @@ -709,4 +734,14 @@ class Array end nil end + + ## + # call-seq: + # ary.to_ary -> ary + # + # Returns +self+. + # + def to_ary + self + end end -- cgit v1.2.3