Commit 7ed47c12 authored by Jun Hiroe's avatar Jun Hiroe

Array#rotate

parent b20d711c
...@@ -351,4 +351,35 @@ class Array ...@@ -351,4 +351,35 @@ class Array
end end
self self
end 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 end
...@@ -146,3 +146,13 @@ assert("Array#reverse_each") do ...@@ -146,3 +146,13 @@ assert("Array#reverse_each") do
true true
end end
end end
assert("Array#rotate") do
a = ["a", "b", "c", "d"]
assert_equal ["b", "c", "d", "a"], a.rotate
assert_equal ["a", "b", "c", "d"], a
assert_equal ["c", "d", "a", "b"], a.rotate(2)
assert_equal ["b", "c", "d", "a"], a.rotate(-3)
assert_equal ["c", "d", "a", "b"], a.rotate(10)
assert_equal [], [].rotate
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment