And in Python you can write something like:
sum([p.price for p in products if p.type == "x"])
Excuse untested code from phone, but I like it better than the ruby version.I find the order of iteration in Python for comprehensions totally confusing every time. If you want to convert:
for a in x: pass
into a comprehension, you write: [pass for a in x]
Simple, right? So to convert for a in x: for b in y: pass
I obviously write: [pass for b in y for a in x]
Bzzt. Nope, you have to write it in middle-endian order to get the same behaviour.FYI, you can leave off the square brackets for a small performance boost. That turns it from a list comprehension into a generator expression, which is lazily evaluated and doesn't create a list container (which would immediately be thrown out anyway). It's like the difference between range(n) and xrange(n).
Nice, thanks for the tip.
I guess it's a personal style choice, the Python code is more performant(less iterations over the data set), but I like the ruby version better.
products.select { |product| product.type == 'x' }.map(&:price).reduce(:+)