forked from rubyworks/facets
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1ea0065
commit c2a0cad
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |