42 ms·
No, because that is equivalent to k[v] || (k[v] = k[v-1] + k[v-2]) And that first k[v] (unlike k.key?(v)) will trigger the Hash.new block again, so it'll
by vidarh 3y ago
No, because that is equivalent to
k[v] || (k[v] = k[v-1] + k[v-2])
And that first k[v] (unlike k.key?(v)) will trigger the Hash.new block again, so it'll recurse until it runs out of stack. But neither check is necessary, because the Hash.new block will only ever get called if k.key?(v) is false.
If you want a more compact version, you could do:
fib = Hash.new do |k,v|
next 1 if v == 0 || v == 1
k[v] = k[v-1] + k[v-2]
end