Navigation Menu

Skip to content

Commit

Permalink
String#rotate
Browse files Browse the repository at this point in the history
  • Loading branch information
cielavenir committed Feb 8, 2014
1 parent 1ea0065 commit c2a0cad
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/core/facets/string/rotate.rb
@@ -0,0 +1,26 @@
class String

# Rotate string to the left with count.
# Specifying negative number indicates rotation to the right.
#
# 'abcdefgh'.rotate(2) #=> 'cdefghab'
# 'abcdefgh'.rotate(-2) #=> 'ghabcdef'
#
# CREDIT: T. Yamada

def rotate(count=1)
count+=self.length if count<0
self.slice(count,self.length-count)+self.slice(0,count)
end

# Destructive version of String#rotate
#
# s='abcdefgh'
# s.rotate!(2)
# s.should eq 'cdefghab'
#
# CREDIT: T. Yamada

def rotate!(count=1) self.replace(self.rotate(count)) end

end
31 changes: 31 additions & 0 deletions test/core/string/test_rotate.rb
@@ -0,0 +1,31 @@
covers 'facets/string/rotate'

test_case String do

method :rotate do

test 'rotates left' do
'abcdefgh'.rotate(2).assert == 'cdefghab'
end
test 'rotates right' do
'abcdefgh'.rotate(-2).assert == 'ghabcdef'
end

end

method :rotate! do

test 'rotates left' do
s='abcdefgh'
s.rotate!(2)
s.assert == 'cdefghab'
end
test 'rotates right' do
s='abcdefgh'
s.rotate!(-2)
s.assert == 'ghabcdef'
end

end

end

0 comments on commit c2a0cad

Please sign in to comment.