Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something infinitely many times with an index

In more ruby way of doing project euler #2 , part of the code is

while((v = fib(i)) < 4_000_000)
  s+=v if v%2==0
  i+=1
end

Is there a way to change i += 1 into a more functional programming style construct?

The best I can think of is

Float::MAX.to_i.times do |i|
  v = fib(i)
  break unless v < 4_000_000
  s += v if v%2==0
end

because you can't call .times on a floating point number.

like image 943
Andrew Grimm Avatar asked Feb 29 '12 23:02

Andrew Grimm


1 Answers

Numeric.step has default parameters of infinity (the limit) and 1 (the step size).

1.step do |i|
  #...
end

For fun, you might even want to try

1.step.size
like image 124
steenslag Avatar answered Sep 21 '22 18:09

steenslag