method ruby return true or false

21,329

Solution 1

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

Solution 2

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
Share:
21,329
hyperrjas
Author by

hyperrjas

Code Lover Ror, Nodejs, React/Redux, Mongodb/Mysql/GraphQl

Updated on July 05, 2022

Comments

  • hyperrjas
    hyperrjas almost 2 years

    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