2012-01-29 94 views
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 #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。如果每個帖子都被關注,我希望返回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

我沒有測試過,但你也能夠使用'break'上緊接在'value = false'後面的行,以防止額外循環 – SimonMayer 2012-01-29 13:13:41

+0

對於你的carma,我接受你的迴應。它確實工作正常:D。非常感謝你。 – hyperrjas 2012-01-29 14:02:18

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 2012-01-29 14:02:36

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 2012-01-29 14:04:05

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 2012-01-29 14:57:13