diff options
| author | takahashim <[email protected]> | 2015-11-23 19:51:02 +0900 |
|---|---|---|
| committer | takahashim <[email protected]> | 2015-11-24 08:39:39 +0900 |
| commit | 621487a0cd8acc5bbec73c98ebbb23c519ba6e6d (patch) | |
| tree | 7c28981ea380b3fa0f1bc7f9e59f98e7b2a0cb2d /mrbgems/mruby-array-ext | |
| parent | 625a3fee7729a12b0ff613e80b7b45ba0e2f086b (diff) | |
| download | mruby-621487a0cd8acc5bbec73c98ebbb23c519ba6e6d.tar.gz mruby-621487a0cd8acc5bbec73c98ebbb23c519ba6e6d.zip | |
add {Array|Hash|String}.try_convert
Diffstat (limited to 'mrbgems/mruby-array-ext')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 35 | ||||
| -rw-r--r-- | mrbgems/mruby-array-ext/test/array.rb | 12 |
2 files changed, 47 insertions, 0 deletions
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,6 +1,31 @@ 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 # ary.uniq! { |item| ... } -> 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 diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb index 6c2f52379..f17cb80e1 100644 --- a/mrbgems/mruby-array-ext/test/array.rb +++ b/mrbgems/mruby-array-ext/test/array.rb @@ -1,6 +1,13 @@ ## # Array(Ext) Test +assert("Array.try_convert") do + assert_nil Array.try_convert(0) + assert_nil Array.try_convert(nil) + assert_equal [], Array.try_convert([]) + assert_equal [1,2,3], Array.try_convert([1,2,3]) +end + assert("Array#assoc") do s1 = [ "colors", "red", "blue", "green" ] s2 = [ "letters", "a", "b", "c" ] @@ -298,3 +305,8 @@ assert("Array#index (block)") do assert_nil (1..10).to_a.index { |i| i % 5 == 0 and i % 7 == 0 } assert_equal 34, (1..100).to_a.index { |i| i % 5 == 0 and i % 7 == 0 } end + +assert("Array#to_ary") do + assert_equal [], [].to_ary + assert_equal [1,2,3], [1,2,3].to_ary +end |
