如何编写一个方法来有效地实现这个功能?Ruby如何编写连续的分区
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
?)
你的问题,如果你的例子会比较清楚((52/2)/ 4)/ 2 =>((26.0)/ 4)/ 2 => 6.5/2 = > 3.25'。 –
@CarySwoveland我删除了我的评论。我实际上是参考了这个风格指南,并且完全得到了向''inject''后面的'reduce'。谢谢你指出。 – Dbz