Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 494 Vote(s) - 3.54 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mapping values from two array in Ruby

#1
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.
Reply

#2
weights = [1,2,3]
data = [10,50,30]

require 'matrix'
Vector[*weights].inner_product Vector[*data] # => 200

Reply

#3
The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but here's one approach you could use:


weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation

sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations
Reply

#4
An alternative for the map that works for more than 2 arrays as well:

def dot(*arrays)
arrays.transpose.map {|vals| yield vals}
end

dot(weights,data) {|a,b| a*b}

# OR, if you have a third array

dot(weights,data,offsets) {|a,b,c| (a*b)+c}

This could also be added to Array:

class Array
def dot
self.transpose.map{|vals| yield vals}
end
end

[weights,data].dot {|a,b| a*b}

#OR

[weights,data,offsets].dot {|a,b,c| (a*b)+c}


















Reply

#5
@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(&:+)
Reply

#6
In Ruby 1.9:

weights.zip(data).map{|a,b| a*b}.reduce(:+)

In Ruby 1.8:

weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }
Reply

#7
Ruby has a <code>map</code> method (a.k.a. the <code>collect</code> method), which can be applied to any <code>Enumerable</code> object. If <code>numbers</code> is an array of numbers, the following line in Ruby:

numbers.map{|x| x + 5}

is the equivalent of the following line in Python:

map(lambda x: x + 5, numbers)

For more details, see [here][1] or [here][2].


[1]:

[To see links please register here]

"Enumerable#collect / Enumerable#map"
[2]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through