代碼
def insert_new(arr, new_instance)
arr.insert(arr.index { |instance| new_instance.score >= instance.score } || -1,
new_instance)
end
例
class A
def initialize(user, score)
@user, @score = user, score
end
end
arr = [A.new("Hank", 10), A.new("Lois", 8), A.new("Billy-Bob", 6),
A.new("Trixy", 4)]
#=> [#<A:0x007fad7b02fd70 @user="Hank", @score=10>,
# #<A:0x007fad7b02fcf8 @user="Lois", @score=8>,
# #<A:0x007fad7b02fc80 @user="Billy-Bob", @score=6>,
# #<A:0x007fad7b02fbe0 @user="Trixy", @score=4>]
insert_new(arr, A.new("Hubert", 7))
#=> [#<A:0x007fad7a027450 @user="Hank", @score=10>,
# #<A:0x007fad7a0273b0 @user="Lois", @score=8>,
# #<A:0x007fad7a850b90 @user="Hubert", @score=7>,
# #<A:0x007fad7a027310 @user="Billy-Bob", @score=6>,
# #<A:0x007fad7a027270 @user="Trixy", @score=4>]
insert_new(arr, A.new("Zelda", 2))
#=> [#<A:0x007fad7a027450 @user="Hank", @score=10>,
# #<A:0x007fad7a0273b0 @user="Lois", @score=8>,
# #<A:0x007fad7a850b90 @user="Hubert", @score=7>,
# #<A:0x007fad7a027310 @user="Billy-Bob", @score=6>,
# #<A:0x007fad7a027270 @user="Trixy", @score=4>,
# #<A:0x007fad7b876128 @user="Zelda", @score=2>]
insert_new(arr, A.new("Slim", 8))
# Slim is inserted between Hank and Lois
insert_new(arr, A.new("Rhonda", 8))
# Rhonda is inserted between Hank and Slim
注意
注意,塞爾達被插入到最後。在這種情況下,
arr.index { |instance| new_instance.score >= instance.score } #=> nil
所以索引-1
使用(... || -1
),這意味着該值是arr
的最後一個元素之後插入。見String#insert。
我認爲這個解決方案可能適合您的目的:http://stackoverflow.com/questions/23481725/using-bsearch-to-find-index-for-inserting-new-element-into-sorted-array –