【问题标题】:method ruby return true or false方法 ruby​​ 返回 true 或 false
【发布时间】:2012-02-21 15:04:11
【问题描述】:

如果每个帖子都被一个人关注,我想从方法 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

【问题讨论】:

    标签: ruby count block each ruby-1.9.2


    【解决方案1】:

    您应该使用Enumerable#all? 方法检查列表的所有元素是否与谓词(返回布尔值的块)中定义的条件匹配。

    全部? [{|对象|块 } ] → 真或假

    将集合的每个元素传递给给定的块。方法 如果块从不返回 false 或 nil,则返回 true。如果块是 没有给出,Ruby 添加了一个隐式块 {|obj| obj}(仅此而已? 仅当没有集合成员为 false 或 无。)

    def number_of_posts_that_are_followed
      User.find(params[:id]).posts.all? {|post| current_user.follows? post }
    end
    

    【讨论】:

      【解决方案2】:

      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】:
        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
        

        【讨论】:

          【解决方案4】:
          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
          

          【讨论】:

          • 我没有测试过,不过你也可以在value = false后面紧接着使用break,防止多余的循环
          • 对于您的卡玛,我接受您的回复。它确实工作正常:D。非常感谢。
          猜你喜欢
          • 1970-01-01
          • 2021-05-17
          • 1970-01-01
          • 1970-01-01
          • 2019-12-04
          • 1970-01-01
          • 2018-11-09
          • 2011-01-17
          • 2017-09-16
          相关资源
          最近更新 更多