hyp*_*jas 1 ruby each block count ruby-1.9.2
我想从一个方法ruby中获取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
Run Code Online (Sandbox Code Playgroud)
问题是如果第一个帖子(在第一次迭代中)后跟current_user,则此方法返回true.如果每个帖子都被跟踪,我想要返回true,否则返回false.
我试过把这样的计数:
count = user_to_be_followed.posts.count
Run Code Online (Sandbox Code Playgroud)
你应该使用Enumerable#all?检查列表的所有元素是否与谓词中定义的条件匹配的方法(返回布尔值的块).
所有?[{| OBJ | 阻止}] →真或假
将集合的每个元素传递给给定的块.如果块永远不返回false或nil,则该方法返回true.如果没有给出块,Ruby会添加一个{| obj |的隐式块 obj}(即所有?只有在没有集合成员为false或nil时才会返回true.)
def number_of_posts_that_are_followed
User.find(params[:id]).posts.all? {|post| current_user.follows? post }
end
Run Code Online (Sandbox Code Playgroud)