2012-01-29 103 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