如何写一个方法来高效的实现这个功能?
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
这是我能想到的
def divide_array(array)
return false if array.include?(0)
result = 0
array.each_with_index do |i, index|
break if index >= array.size - 1
result = i.to_f / array[index + 1].to_f
end
result
end
但我认为 Ruby 是一种优雅的语言,它一定是一种更好、更有效的实现方式。 (也许像 reduce
或 inject
?)
最佳答案
确实注入(inject)(或减少),但是 to_f
和除法可以通过 fdiv
一次性完成:
[3,2,1].inject(:fdiv) #=> 1.5
更精确的是转换为 Rationals,并且尽可能晚地转换为 Float。演示:
[3,5,6].map(&:to_f).inject(:/) # => 0.09999999999999999
[3,5,6].map(&:to_r).inject(:/).to_f # => 0.1
正如 sagarpandya82 的评论(对我来说是新的),这种到 Rational 和除法的转换也可以一次性完成,最终:
[3,5,6].inject(:quo).to_f #=> 0.1
关于Ruby如何写一个连续的除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45378935/