diff options
| author | Paolo Bosetti <[email protected]> | 2014-01-10 11:13:47 +0100 |
|---|---|---|
| committer | Paolo Bosetti <[email protected]> | 2014-01-10 11:13:47 +0100 |
| commit | 921e6e24f4e87cf75827b6deba18fc7bbea48d5c (patch) | |
| tree | e5315180a2a4698ff196ebf2b7564ae6dab13437 /mrbgems/mruby-array-ext/mrblib/array.rb | |
| parent | ff9b41cc371d7d5a75e58f62d01180787d21b327 (diff) | |
| download | mruby-921e6e24f4e87cf75827b6deba18fc7bbea48d5c.tar.gz mruby-921e6e24f4e87cf75827b6deba18fc7bbea48d5c.zip | |
Added rewrite of Array#[] to mruby-array-ext gem, so that arrays can be sliced
with Ranges (as a[1..-2])
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 337cef632..f8d89dc7b 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -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 |
