每个块中的方法ruby中的数组

时间:2012-02-01 18:20:30

标签: ruby-on-rails ruby loops foreach

我有这个方法

def last_board

 user = current_user #current_user

 boards = current_user.boards #return every boards that belongs to current_user e.g. [#<Board _id: 4f2968ac1d41c81c7c000063, _type: "Board", created_at...] 

 followers = user.all_followers #return every followers of user [#<User _id: 4f2862b21d41c847e200005b, _type: "User" reset_password_sent_at: nil, confirmation_token: nil,...]

 followers.each do |follower|
  boards.each do |board| 
  # I want to be a follower of user, if I am following at least one board of this user  
  #I want run this code, "follower.unfollow(user)", only if follower does not following any user's board.
 #this method "follower.follower_of?(board)" return true or false if follower follow board
  end       
 end

1 个答案:

答案 0 :(得分:0)

你可以这样吗

followers.each do |follower|
     is_having_any_board = false
     follower.boards.each do |follower_board|
         boards.each do |board| 
            if(follower_board.id == board.id)#delete last )
               is_having_any_board = true
               break;
            end
         end
     end

     if(is_having_any_board)
         follower.follow(user)
     else
         follower.unfollow(user)
     end
end