这是一个比看起来更棘手的问题。我定义了以下测试:
describe Array do
describe '.promote' do
subject(:array) { [1, 2, 3] }
it { expect(array.promote(2)).to eq [2, 1, 3] }
it { expect(array.promote(3)).to eq [3, 1, 2] }
it { expect(array.promote(4)).to eq [1, 2, 3] }
it { expect((array + array).promote(2)).to eq [2, 1, 3, 1, 2, 3] }
end
end
sort_by
@Duopixel 提出的建议很优雅,但[3, 2, 1]
可以用于第二次测试。
class Array
def promote(promoted_element)
sort_by { |element| element == promoted_element ? 0 : 1 }
end
end
@tadman 使用delete
,但这会删除所有匹配的元素,因此第四个测试的输出是[2, 1, 3, 1, 3]
.
class Array
def promote(promoted_element)
if (found = delete(promoted_element))
unshift(found)
end
self
end
end
我尝试使用:
class Array
def promote(promoted_element)
return self unless (found = delete_at(find_index(promoted_element)))
unshift(found)
end
end
但这在第三次测试中失败了,因为delete_at
无法处理 nil。最后,我决定:
class Array
def promote(promoted_element)
return self unless (found_index = find_index(promoted_element))
unshift(delete_at(found_index))
end
end
谁知道一个简单的想法promote
会如此棘手?