Skip to main content
Add encouragement to use reduce
Source Link
Anonymous
  • 2.2k
  • 10
  • 14

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.

Yes, there's a built-in count method for this:

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.

There's a built-in count method which 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.

Source Link
Anonymous
  • 2.2k
  • 10
  • 14

Yes, there's a built-in count method for this:

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.