2017-04-04 3 views
1

이 객체의 속성 중 하나로 정렬 된 객체 배열이 있고 그 객체에 의해 결정되는 위치에 다른 객체를 삽입하려고합니다. 개체의배열 내용을 기반으로 특정 위치에 배열에 삽입하십시오. Ruby

기본적으로, 무엇인가 :
bar = User(score: 6)
을 올바른 인덱스에서 2

내가 밀어 수있는 인덱스이 경우 있도록 :
foo = [User(score: 10), User(score: 8), User(score: 5), User(score: 1)]
그리고 그 배열에, 나는 삽입 할 배열 및 다음 sort_by,하지만이 문제 (인덱스를 정의하는 블록을 전달할 수있는 일종의 삽입 방법)에 대한 더 나은 솔루션이 있는지 궁금 해서요. 사전 :

+0

이 솔루션이 귀하의 목적에 적합 할 수 있다고 생각합니다. http://stackoverflow.com/questions/23481725/using-bsearch-to-find-index-for-inserting-new-element-into-sorted-array –

답변

0

코드

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는 값 arr의 마지막 요소 이후에 삽입되는 것을 의미한다 (... || -1)를 사용 하였다. String#insert을 참조하십시오.

+1

안녕하세요 캐리, 왜 당신이 downvoted되고 있는지 모르지만, 이것은 최고의 대답입니다. 기본'-1'은 정말 영리합니다. 하하. 포괄적 인 예제를 가져 주셔서 감사합니다. 노력에 감사드립니다! 당신은 정말로 나를 도왔습니다 :) – Jeroen

1

당신은 인덱스를 발견하고 전체 종류를 피하기 싶다면 다음 삽입 할 수있는

감사합니다. 뭔가 같은 -

insert_index = foo.index { |x| x.score <= new_user.score } || -1 
foo.insert(insert_index, new_user) 
+1

이것은 실제로 스마트 솔루션입니다! 여기에서 유일한 문제는 new_user.score가 항상 다른 점수보다 작 으면 끝까지 삽입되지 않아야한다는 것입니다. Cary Swoveland도 비슷한 대답을 주었고 foo.index가 nil을 반환하면 기본값 -1을 추가했습니다. 하지만 이것은 분명 올바른 접근 방식입니다. 감사 라훌 :) – Jeroen

+0

좋은 잡기. 이 경우를 설명하기 위해 편집했습니다. – Rahul

관련 문제