Search code examples
rubyblock

Using a block to find values matching criteria


To me this makes perfect sense:

triple = dice.collect {|value| if (dice.count(value) >= 3)} ---> Syntax error

OR

triple = dice.collect {|value| dice.count(value) >= 3} ----> Array of true/false

I want the value of the number, not the true or falsity of dice.count(). I know there must be a simple way of doing this.


Solution

  • It sounds like you want Array#select, not Array#collect (also known as Array#map).

    collect/map will take each value and put the results of your block into an array. This is why you're seeing an array of true/false.

    select will take each value, and return it as a member of an array if the block evaluates to true:

    triple = dice.select{ |value| dice.count(value) >= 3 }