开发者

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.


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 }


Your block needs to return whatever it is you want in the final array.

triple = dice.collect {|value| 
  if dice.count(value) >= 3
    dice.count(value)
  end
}

Note that this will return nil for elements < 3 (though you can add an else to return 0 or something). If you only want elements that match your query, you'll need to use dice.select()


As for your first code snippet,

triple = dice.collect {|value| THE_CODE_BLOCK_STARTS_HERE }

Thus, if (dice.count(value) >= 3) is an incomplete if statement. That's why you get syntax error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜