Ruby how to write a consecutive division -
how write method achieve function efficiently?
divide_array([a,b,c]) # return a.to_f / b.to_f / c.to_f divide_array([a,b,c,d,e]) # return a.to_f / b.to_f / c.to_f / d.to_f / d.to_f here can image
def divide_array(array) return false if array.include?(0) result = 0 array.each_with_index |i, index| break if index >= array.size - 1 result = i.to_f / array[index + 1].to_f end result end but thought ruby elegant language, must better , efficient way achieve that. (maybe reduce or inject?)
inject (or reduce) indeed, to_f , division can done in 1 go fdiv:
[3,2,1].inject(:fdiv) #=> 1.5 more precise converting rationals, , convert float late possible. demo:
[3,5,6].map(&:to_f).inject(:/) # => 0.09999999999999999 [3,5,6].map(&:to_r).inject(:/).to_f # => 0.1 as sagarpandya82 comments (and new me), conversion rational , division can done in 1 go, culminating in:
[3,5,6].inject(:quo).to_f #=> 0.1
Comments
Post a Comment