3 ms·
Is this: def fibonacci(max=Float::INFINITY) # ... while i < max # ... end end better than this: def fibonacci(max=nil)
by hk__2 13y ago
Is this:
def fibonacci(max=Float::INFINITY)
# ...
while i < max
# ...
end
end
better than this:
def fibonacci(max=nil)
# ...
while max && i < max
# ...
end
end
?
(genuine question)
- Xylakant 13y agoyes. The first one does what it's intended to, the second plain fails :) Voice-of-Evening:~ $ irb irb(main):001:0> max=Float::INFINITY => Infinity irb(main):002:0> i = 0 => 0 irb(main):003:0> i < max => true irb(main):004:0> max = nil => nil irb(main):005:0> max && i < max => nil The second version will only provide any result when a specific max value was given, while the first one will loop into infinity.
- nilved 13y agoWhat you meant is `while !max || max < i`, but the answer is the same: the former will perform better because it only makes one comparison for each iteration of the loop. The latter needs to additionally check the existence of max.