Question

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
Was it helpful?

Solution

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

OTHER TIPS

You should use Enumerable#all? method to check that all elements of the list match condition defined in predicate (block that returns boolean value).

all? [{|obj| block } ] → true or false

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is all? will return true only if none of the collection members are false or nil.)

def number_of_posts_that_are_followed
  User.find(params[:id]).posts.all? {|post| current_user.follows? post }
end
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

A little refactoring of SimonMayer's :

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

EDIT: Even shorter, ruby-style :

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top