summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext/mrblib
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2014-04-11 23:45:52 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-04-11 23:45:52 +0900
commitfe55b9dd1cca607398454bd2d432b2482f40cbef (patch)
tree603686c977831c1b60932eaad6ffd4dd9dcd07cb /mrbgems/mruby-array-ext/mrblib
parent92156b46194591ea7608ee9c587c6e29cacd25ea (diff)
parent7ed47c1223e6b0c37a5e5e1a14e5fd31ba59bc04 (diff)
downloadmruby-fe55b9dd1cca607398454bd2d432b2482f40cbef.tar.gz
mruby-fe55b9dd1cca607398454bd2d432b2482f40cbef.zip
Merge pull request #2045 from suzukaze/add-array.rotate
Array#rotate
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb31
1 files changed, 31 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb
index 2e66c5fbc..f6adc5255 100644
--- a/mrbgems/mruby-array-ext/mrblib/array.rb
+++ b/mrbgems/mruby-array-ext/mrblib/array.rb
@@ -351,4 +351,35 @@ class Array
end
self
end
+
+ ##
+ # call-seq:
+ # ary.rotate(count=1) -> new_ary
+ #
+ # Returns a new array by rotating +self+ so that the element at +count+ is
+ # the first element of the new array.
+ #
+ # If +count+ is negative then it rotates in the opposite direction, starting
+ # from the end of +self+ where +-1+ is the last element.
+ #
+ # a = [ "a", "b", "c", "d" ]
+ # a.rotate #=> ["b", "c", "d", "a"]
+ # a #=> ["a", "b", "c", "d"]
+ # a.rotate(2) #=> ["c", "d", "a", "b"]
+ # a.rotate(-3) #=> ["b", "c", "d", "a"]
+
+ def rotate(count=1)
+ ary = []
+ len = self.length
+
+ if len > 0
+ idx = (count < 0) ? (len - (~count % len) - 1) : (count % len) # rotate count
+ len.times do
+ ary << self[idx]
+ idx += 1
+ idx = 0 if idx > len-1
+ end
+ end
+ ary
+ end
end