diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-01-10 04:49:57 -0800 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-01-10 04:49:57 -0800 |
| commit | e63c1e1d493bb97d4a299e2ab55c8aa6e46681e0 (patch) | |
| tree | a1f8bbe1b17f694406f965bc9dba8b19bb988d33 /mrbgems/mruby-array-ext | |
| parent | 3fff0e20258648a098477ed68661df07ab0d48dd (diff) | |
| parent | 921e6e24f4e87cf75827b6deba18fc7bbea48d5c (diff) | |
| download | mruby-e63c1e1d493bb97d4a299e2ab55c8aa6e46681e0.tar.gz mruby-e63c1e1d493bb97d4a299e2ab55c8aa6e46681e0.zip | |
Merge pull request #1655 from pbosetti/master1.0.0
Added rewrite of Array#[] to mruby-array-ext gem
Diffstat (limited to 'mrbgems/mruby-array-ext')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 32 | ||||
| -rw-r--r-- | mrbgems/mruby-array-ext/test/array.rb | 7 |
2 files changed, 39 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 diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb index 1c441cec4..8a6f50fe4 100644 --- a/mrbgems/mruby-array-ext/test/array.rb +++ b/mrbgems/mruby-array-ext/test/array.rb @@ -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 |
