Question
I'm wondering if there's a way to do what I can do below with Python, in Ruby:
sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.
Answer
@Michiel de Mare
Your Ruby 1.9 example can be shortened a bit further:
weights.zip(data).map(:*).reduce(:+)
Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:
weights.zip(data).map(&:*).reduce(&:+)
< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/3281/" >Mapping values from two array in Ruby< /a>
0 comments:
Post a Comment