0

This is related to a closed question where some users kindly tried to helped me but at the time I couldn't reproduce the problem exactly.

STARTING POINT

output = [{:selected_person=>true,
           :full_name=>"Fn G猫gèksöugöynúõr Ln Ýüćėūpàøehwìėwo",
           :address_1=>"Trzy Lipy", :address_2=>"20", 
           :postal=>"34-567",
           :city=>"Gdańsk", :country_code=>"PL"}, 
          {:selected_person=>true,
            :full_name=>"Fellow Fellow Last Name", :minor=>false}]

WHAT I WANT TO ACHIEVE

Count the number of occurrences of :selected_person as true in the output

WHAT I HAVE NOW

A. Returns '2' (counts the number of occurrences no matter the value)

output.count { |h| h[:selected_person] = true }

B. Returns '0'

output.count { |h| h[:selected_person]}

EDIT NOTES:

After saving, I didn't notice that the example changed so the link shows a version where version B would work, as pointed out in one answer, but the correct output/starting point is the one pasted here in the question and in the screenshot

Correct Context Example

1 Answer 1

1

By using a single equal in your block, you're setting :selected_person to true for each item, not checking it if is true.

Either of these would work. Make sure you're running it against a new output, not one that may have been mutated by the single equals experiment.

output.count { |h| h[:selected_person] == true }
output.count { |h| h[:selected_person] }
Sign up to request clarification or add additional context in comments.

4 Comments

thank you for the quick answer but, my bad, I hadn't noticed that when I saved the code in the provided link, it changed the code so indeed, your suggestions would work in that case but not in my case (screenshot and output code in the question). Please check my edited question
The code you link to has a different issue. You're setting :selected_pax but counting :selected_person. count returns zero because :selected_person is falsy (it isn't set at all) for both objects.
Yes, I copied from another window where I was testing and didn't noticed. All corrected now both the problem and description/screenshot match the explanation :)
The code in the question and the code in the REPL are not the same. When I run the code in the REPL, it returns 1 for the count, which would be expected when one of the objects has selected_pax set to true.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.