Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return true or false from a block method inside a method

Tags:

ruby

An Item has_many Pieces. I have two methods, one that finds out if the Piece is available and one that finds out if an Item has available pieces.

  # in piece.rb
  def available?(current_user, piece)
    if piece.status == 1
      true
    elsif piece.status == 2
      false
    elsif piece.status == 3
      true if piece.friend_id == current_user.id
    end
  end

  #in item.rb
  def available?(current_user, user, item)
    false
      item.pieces.each do |piece|
        if piece.available?(current_user, piece)
          true
        end
      end
  end

My available? method in Item is wrong. I want it to return true if an Item has available pieces, and false if not. Theory behind my code is that the method returns false unless there is a piece that returns true. When I do it in the console all I get are the pieces in a hash, not true or false.

Can anyone solve my problem or tell me a better way to do this?

like image 781
Dol Avatar asked Mar 31 '26 15:03

Dol


2 Answers

Use Enumerable#any?:

def available?(current_user, user, item)
  item.pieces.any? do |piece|
    piece.available?(current_user, piece)
  end
end
like image 67
tokland Avatar answered Apr 02 '26 07:04

tokland


If you need to check whether item has at least one available piece, the method can look like this:

def available?(current_user, user, item)
  item.pieces.each do |piece|
    return true if piece.available?(current_user, piece)
  end
  false
end
like image 32
Hck Avatar answered Apr 02 '26 06:04

Hck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!