SupremeA SupremeA - 5 months ago 23
Ruby Question

Enumerable#find_all with exceptions Ruby

I am trying to find all of the amounts that are negative in an array excluding objects that are in certain categories. Here is a sample of the array.

@transactions =
[{"amount"=>-20, "name"=>"DEPOSIT", "category"=>["BENEFITS"], "category_id"=>"21007000"},
{"amount"=>-0.8, "name"=>"XFER", "category"=>["Transfer", "Credit"], "category_id"=>"2106381"},
{"amount"=>-20, "name"=>"DEPOSIT", "category"=>["Transfer", "Deposit"],
"category_id"=>"21007000"},
{"amount"=>-1, "name"=>"XFER", "category"=>["Transfer", "Credit"],
"category_id"=>"21005000"},
{"amount"=>300.80, "name"=>"XFER", "category"=>"Food", "category_id"=>"2106381"}]


So far I have something like this but the syntax is wrong and it does not work. i am not even sure I can use a "condition" on a find_all block.

items = @transactions.find_all ( { |t| t.fetch('amount') != t.fetch('amount').abs, :conditions => [ t.fetch('category_id') == '2106381' || t.fetch('category') == ["Benefits"] != ?, any? ]})


So find all the objects with a negative number for amount and exclude the objects from that list that have the following category id or category name.

With an output of only the objects that are negative and dont have the benefits name or category id "2106381"

Answer

Your question isn't especially clear, but I suspect this does what you want:

@transactions.select do |t|
  t["amount"] < 0 &&
    !(t["category_id"] == "2106381" || t["category"] == "Benefits")
end

Alternatively, this is a bit more declarative (but slightly less efficient):

@transactions.select(&:negative?)
  .reject {|t| t["category_id"] == "2106381" || t["category"] == "Benefits" }