How can I perform element-wise multiplication for Ruby arrays? -


courses, credits , points ruby arrays equal size.

gpa = (([credits, courses, points].transpose.map {|x| x.reduce(:*)}).inject{|sum,x| sum + x }).round(2) 

this method prompted error message when trying run it.

error message:

in 'each': undefined method '*' nil:nilclass (nomethoderror) 

from error message, seems of data nil.

perhaps can attempt force data floats.

it's not ideal, might end silent errors, it's worth shot.

try:

[credits, courses, points].transpose.map {|a| a.map {|n| n.to_f} } .map { |x| x.reduce(:*) } .inject{|sum, x| sum + x} .round(2) 

it works me strings , weird data (although incompatible data converted zeros, effecting math).


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -