如何从枚举器中排除第二个结尾

时间:2014-09-26 21:52:04

标签: ruby ienumerator

我需要一个Enumerator来覆盖从na的{​​{1}}位数字。我需要一个带有步骤b - (b - a) / n.to_f()的左闭合右开间隔。我怎么能得到它?

我使用(b - a) / n.to_f(),但a.step(b, (b - a) / n.to_f())会返回step,该Enumerator会重复n + 1个数字,包括两端ab

1 个答案:

答案 0 :(得分:1)

def get_steps(a,b,n)
  step = (b - a) / n.to_f
  a.step(b - step, step)   # or a.step(nil, step).take(n)
end

get_steps(2,4,5)       #=> <Enumerator:... >
get_steps(2,4,5).to_a  #=> [2.0, 2.4, 2.8, 3.2, 3.6]
相关问题