Added rewrite of Array#[] to mruby-array-ext gem, so that arrays can be sliced
authorPaolo Bosetti <[email protected]>
Fri, 10 Jan 2014 10:13:47 +0000 (10 11:13 +0100)
committerPaolo Bosetti <[email protected]>
Fri, 10 Jan 2014 10:13:47 +0000 (10 11:13 +0100)
with Ranges (as a[1..-2])

mrbgems/mruby-array-ext/mrblib/array.rb
mrbgems/mruby-array-ext/test/array.rb

index 337cef6..f8d89dc 100644 (file)
@@ -201,4 +201,36 @@ class Array
       self.replace(result)
     end
   end
+  
+  ##
+  # call-seq:
+  #    ary[rng]    -> ary slice
+  #
+  # Remeturns a slice of +ary+ according to the Range instance +rng+.
+  #
+  #    a = [ "a", "b", "c", "d", "e" ]
+  #    a[1]     => "b"
+  #    a[1,2]   => ["b", "c"]
+  #    a[1..-2] => ["b", "c", "d"]
+  #
+  def [](idx, len=nil)
+    case idx
+    when Range
+      if idx.last < 0 then
+        len = self.length - idx.first + idx.last + 1
+      else
+        len = idx.last - idx.first + 1
+      end
+      return self.slice(idx.first, len)
+    when Numeric
+      if len then
+        return self.slice(idx.to_i, len.to_i)
+      else
+        return self.slice(idx.to_i)
+      end
+    else
+      self.slice(idx)
+    end
+  end
+  
 end
index 1c441ce..8a6f50f 100644 (file)
@@ -107,3 +107,10 @@ assert("Array#compact!") do
   a.compact!
   a == [1, "2", :t, false]
 end
+
+assert("Array#[]") do
+  a = [ "a", "b", "c", "d", "e" ]
+  a[1.1]   == "b" and
+  a[1,2]   == ["b", "c"] and
+  a[1..-2] == ["b", "c", "d"]
+end