Created
November 30, 2009 23:15
-
-
Save steve9001/245867 to your computer and use it in GitHub Desktop.
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
class Array | |
def promote_element(e) | |
i = self.index(e) | |
return self if i == 0 or i == nil | |
result = self.slice(0, i-1) | |
result << e | |
result << self[i-1] | |
result.concat(self.slice(i+1, self.length)) | |
end | |
def demote_element(e) | |
i = self.index(e) | |
return self if i == self.length - 1 or i == nil | |
result = self.slice(0, i) | |
result << self[i+1] | |
result << e | |
result.concat(self.slice(i+2, self.length)) | |
end | |
def remove_element(e) | |
i = self.index(e) | |
return self if i == nil | |
result = self.slice(0, i) | |
result.concat(self.slice(i+1, self.length)) | |
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
require 'spec_helper' | |
describe Array do | |
before do | |
@list = [:one, :two, :three] | |
end | |
describe "promote_element" do | |
it "promotes the element" do | |
@list.promote_element(:two).should == [:two, :one, :three] | |
@list.promote_element(:three).should == [:one, :three, :two] | |
end | |
it "returns self when promoting the first" do | |
@list.promote_element(:one).should == @list | |
end | |
it "returns self when promoting non-element" do | |
@list.promote_element(:four).should == @list | |
end | |
end | |
describe "demote_element" do | |
it "demotes the element" do | |
@list.demote_element(:two).should == [:one, :three, :two] | |
@list.demote_element(:one).should == [:two, :one, :three] | |
end | |
it "returns self when demoting the last" do | |
@list.demote_element(:three).should == @list | |
end | |
it "returns self when demoting non-element" do | |
@list.demote_element(:four).should == @list | |
end | |
end | |
describe "remove element" do | |
it "removes the element" do | |
@list.remove_element(:one).should == [:two, :three] | |
@list.remove_element(:two).should == [:one, :three] | |
@list.remove_element(:three).should == [:one, :two] | |
end | |
it "returns self when removing non-element" do | |
@list.remove_element(:four).should == @list | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment