三項演算子
最近、三項演算子をつなげて書くCodeを見かけた.
そういえば、そんなCode書いたことがなかったので、俺もまねしてみた.
リターンで再帰と合わせて使うと、なんだろなぁ.言葉が出てこないw
def search(key, nodes, point=0) return nil unless nodes middle_point = nodes.size / 2 m_value = nodes[middle_point] key == m_value ? point + middle_point : middle_point == 0 ? nil : key < m_value ? search(key, nodes[0..middle_point-1], point) : search(key, nodes[middle_point+1..nodes.size], point+middle_point+1) end describe "binary search" do before(:each) do @a = [1, 4, 55, 99, 100] end it "should return value if found" do search(1, @a).should == 0 search(55, @a).should == 2 search(100, @a).should == 4 end it "should return nil if not found" do search(0, @a).should be_nil search(2, @a).should be_nil search(101, @a).should be_nil end end describe "binary search when array size is 0" do before(:each) do @a = [] end it "should return nil" do search(0, @a).should be_nil end end describe "binary search when array is nil" do before(:each) do @a = nil end it "should return nil" do search(-1, @a).should be_nil end end