Yes, there'sThere's a built-in count
method for thiswhich handles your example cleanly:
names.count {|name| triangles.include?(name.points) }
Also, the accumulator version should use +
, not +=
. reduce
uses the block's return value; there's no need to modify acc
.
In general, though, there's no simpler way to accumulate values than reduce
. It's not very clear, but all of the alternatives are worse.
Don't be afraid of the conditional operator. It's just a different way to spell if...else
.