我希望从方法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
问题是如果第一个帖子(在第一次迭代中)后跟current_user,则此方法返回true。我希望如果每个帖子都被跟踪则返回true,否则返回false。
我试过像这样的计数:
count = user_to_be_followed.posts.count
答案 0 :(得分:8)
您应该使用Enumerable#all?方法检查列表中的所有元素是否与谓词中定义的条件匹配(返回布尔值的块)。
所有? [{| OBJ |阻止}] →真或假
将集合的每个元素传递给给定的块。方法 如果块永远不返回false或nil,则返回true。如果块是 没有给出,Ruby添加了一个隐含的{| obj |块obj}(这就是全部? 仅当没有任何集合成员为false或时,才会返回true 为零。)
def number_of_posts_that_are_followed
User.find(params[:id]).posts.all? {|post| current_user.follows? post }
end
答案 1 :(得分:2)
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
答案 2 :(得分: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
答案 3 :(得分: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