2012-01-29 4 views
0

루비 메소드에서 얻으려는 경우 true 사람마다 모든 게시물을 따르는 경우 이 아닌 경우이면 false입니다.메소드 루비가 true 또는 false를 반환합니다.

def number_of_posts_that_are_followed 
    user_to_be_followed = User.find(params[:id]) #users whose posts, will be followed by another user 
    user_to_be_followed.posts.each do |this_post| 
    if current_user.follows?(this_board) == true #method that returns true if the current_user is following this post of the user whose posts will be followed 
    return true 
    else 
    return false 
    end 
    end 
    end 

문제는 (첫 번째 반복에서) 첫 번째 게시물은 CURRENT_USER 다음 경우이 메소드가 true를 반환한다는 것입니다 :

나는이 방법을 가지고있다. 나는 모든 게시물을 따르거나, 그렇지 않은 경우 false를 되찾기를 원합니다. 내가 시도

이 같은 수를 넣어 :

count = user_to_be_followed.posts.count 

답변

1
def number_of_posts_that_are_followed 
    user_to_be_followed = User.find(params[:id]) #users whose posts, will be followed by another user 
    value = true #will stay true unless changed 
    user_to_be_followed.posts.each do |this_post| 
    if current_user.follows?(this_board) != true 
     value = false 
    end 
    end 
    value #returned 
end 
+0

내가 테스트하지 않은 (즉. 컬렉션 구성원 중 어느 것도 허위 또는 전무없는 경우에만 true를 돌려줍니다? 전부입니다)하지만 당신은 또한에 break''사용할 수 있습니다 여분의 루핑을 막기 위해'value = false' 바로 뒤에 오는 줄 – SimonMayer

+0

당신의 카마를 위해, 나는 당신의 반응을 받아들입니다. 그것은 잘 작동합니다 : D 조. 고맙습니다. – hyperrjas

0

SimonMayer의의 작은 리팩토링 :

def number_of_posts_that_are_followed 
    User.find(params[:id]).posts.each do |this_post| 
    return false unless current_user.follows?(this_post) 
    end 
    true 
end 

편집 : 심지어 짧은, 루비 - 스타일 :

def number_of_posts_that_are_followed 
    User.find(params[:id]).posts.map do |this_post| 
    not current_user.follows?(this_post) 
    end.any? 
end 
+0

감사합니다. 잘 작동합니다. D. 고마워요! – hyperrjas

0
def number_of_posts_that_are_followed 
    user_to_be_followed = User.find(params[:id]) #users whose posts, will be followed by another user 
    user_to_be_followed.posts.each do |this_post| 
    if current_user.follows?(this_board) != true 
     return false 
    end 
    end 
    return true 
end 
+0

잘 작동합니다 : D 매우 고마워요 – hyperrjas

8

목록의 모든 요소가 조건부 (부울 값을 반환하는 블록)에 정의 된 조건과 일치하는지 확인하려면 Enumerable#all? 메서드를 사용해야합니다.

모두? [{| obj | 블록}] → true 또는 false

주어진 블록에 컬렉션의 각 요소를 전달합니다. 메서드는 블록이 false 또는 nil을 반환하지 않으면 true를 반환합니다. 블록이 이 아니라면, Ruby는 {| obj | OBJ}

def number_of_posts_that_are_followed 
    User.find(params[:id]).posts.all? {|post| current_user.follows? post } 
end 
+0

감사합니다. 잘 작동합니다. D. 대단히 감사합니다. – hyperrjas

관련 문제