ruby 方法返回 true 或 false
如果每个帖子都被某个人关注,我想从 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
I want get from a method ruby true if every posts are followed for a people and false if not.
I have this method:
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
The problem is that this method return true if the first post (in the first iteration) its followed by current_user. I want return true if every posts are followed or false if not are followed.
I have tried put a count like this:
count = user_to_be_followed.posts.count
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用Enumerable#all? 方法检查列表的所有元素是否匹配谓词(返回布尔值的块)中定义的条件。
You should use Enumerable#all? method to check that all elements of the list match condition defined in predicate (block that returns boolean value).
对 SimonMayer 的一点重构:
编辑:
甚至更短,红宝石风格:
A little refactoring of SimonMayer's :
EDIT:
Even shorter, ruby-style :