Andrew Grimm
Andrew Grimm

Reputation: 81500

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.

Upvotes: 17

Views: 7497

Answers (3)

steenslag
steenslag

Reputation: 80065

Ruby 2.5 introduced the open-ended Range:

(1..).each do |i|
  #...
end

Upvotes: 5

steenslag
steenslag

Reputation: 80065

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

Upvotes: 19

Josh Lee
Josh Lee

Reputation: 177564

There’s a predefined (in 1.9.2) constant Float::INFINITY, so you could write

1.upto(Float::INFINITY) do |i|
  ...
end

(You could also use Enumerator and take_while, turning the problem inside out to make it look more like Haskell or Python, but take_while is greedy and builds an array.)

Upvotes: 12

Related Questions