Skip to content

Instantly share code, notes, and snippets.

@hiboma
Created July 24, 2012 01:28
Show Gist options
  • Save hiboma/3167355 to your computer and use it in GitHub Desktop.
Save hiboma/3167355 to your computer and use it in GitHub Desktop.
Quiz - Array methods
# -*- encoding: utf-8 -*-
describe Array do
let(:e) { [1,2,3,4,5] }
it "先頭の要素(1)を返すメソッド" do
e[0].should == 1
e.at(0).should == 1
e.first.should == 1
e.fetch(0).should == 1
e.slice(0).should == 1
e.should == [1,2,3,4,5]
end
it "末尾の要素(5)を返すメソッド" do
# 配列のn番目の要素を得るメソッド
e[-1].should == 5
e.at(-1).should == 5
e.last.should == 5
e.fetch(-1).should == 5
e.slice(-1).should == 5
e.fetch(4).should == 5
e.slice(4).should == 5
e.should == [1,2,3,4,5]
end
it "要素をランダムに一個返すメソッド" do
f = e.sample
p f
end
# 一個のメソッドでは無い
it "要素をランダムに一個返すメソッド" do
p e[rand(e.size)]
end
it "全ての要素をランダムに入れ替えるメソッド (例 [1,2,3,4,5] => [2,3,1,4,5] にする)" do
p e.shuffle
end
# これはブロック付きメソッド
it "全ての要素をランダムに入れ替えるメソッド (例 [1,2,3,4,5] => [2,3,1,4,5] にする)" do
p e.sort_by{rand}
end
it "配列を複製するメソッド" do
e.dup.should == e
end
it "配列を空にするメソッド" do
e = []
e.should == []
end
it "配列を空にするメソッド" do
e.clear.should == []
end
# メソッド一個じゃないし...
# oh ...
it "配列を空にするメソッド" do
e.pop
e.pop
e.pop
e.pop
e.pop
e.should == []
end
# oh ...
it "配列を空にするメソッド" do
e.shift
e.shift
e.shift
e.shift
e.shift
e.should == []
end
it "配列を空にするメソッド" do
e.drop(5).should == []
end
it "配列を複製するメソッド" do
e.dup.should == [1,2,3,4,5]
e.clone.should == [1,2,3,4,5]
end
it "末尾に要素(6) を追加する" do
e.push(6).should == [1,2,3,4,5,6]
end
it "末尾に要素(6) を追加する" do
(e << 6).should == [1,2,3,4,5,6]
end
it "先頭に要素(0) を追加する" do
e.unshift(0).should == [0,1,2,3,4,5]
end
it "先頭の要素(1)を削除する ( [2,3,4,5] を作る)" do
e.shift
e.should == [2,3,4,5]
end
it "先頭の要素(1)を削除する ( [2,3,4,5] を作る)" do
e.drop(1).should == [2,3,4,5]
end
it "先頭の要素(1)を削除する ( [2,3,4,5] を作る)" do
(e - [1]).should == [2,3,4,5]
end
it "末尾の要素(5)を削除する ( [1,2,3,4] を作る)" do
e.pop
e.should == [1,2,3,4]
end
it "末尾の要素(5)を削除する ( [1,2,3,4] を作る)" do
e.delete(5)
e.should == [1,2,3,4]
(e - [5]).should == [1,2,3,4]
end
it "末尾の要素(5)を削除する ( [1,2,3,4] を作る)" do
e.delete_at(-1)
e.should == [1,2,3,4]
end
it "末尾の要素(5)を削除する ( [1,2,3,4] を作る)" do
e.delete_at(4)
e.should == [1,2,3,4]
end
it '[1,2,3,4,5] を [1,2,3,"ruby",4,5] にする' do
e.insert(3, "ruby").should == [1,2,3,"ruby",4,5]
end
it '[1,2,3,4,5] を 文字列の "1-2-3-4-5" にする' do
e.join("-").should == "1-2-3-4-5"
end
# 反則
it '[1,2,3,4,5] を 文字列の "1-2-3-4-5" にする' do
def e.to_s
"1-2-3-4-5"
end
e.to_s.should == "1-2-3-4-5"
end
it "[1,3,2,5,4] を [1,2,3,4,5] にする" do
[1,3,2,5,4].sort.should == [1,2,3,4,5]
end
it "[1,2,3,4,5] を [5,4,3,2,1] にする" do
e.reverse.should == [5,4,3,2,1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment