ruby - Why is `loop` not a keyword? What is the use case for `loop` without a block? -


i wondering why loop kernel method rather keyword while , until. there cases want unconditional loop, since loop, being method, slower while true, chose latter when performance important. writing true here looks ugly, , not rubish; loop looks better. here dilemma.

my guess is because there usage of loop not take block , returns enumerator. me, looks unconditional loop can created on spot, , not make sense create such instance of enumerator , later use it. cannot think of use case.

  1. is guess regarding wonder correct? if not, why loop method rather keyword?
  2. what use case enumerator created loop without block?

only ruby's developers can answer first question, guess seems reasonable. second question, sure there use cases. whole point of enumerables can pass them around, which, know, can't while or for structure.

as trivial example, here's fibonacci sequence method takes enumerable argument:

def fib(enum)   a, b = nil, nil    enum.each     a, b = b || 0, ? + b : 1     puts   end   puts "done" end 

now suppose want print out first 7 fibonacci numbers. can use enumerable yields 7 times, 1 returned 7.times:

fib 7.times # => 0 #    1 #    1 #    2 #    3 #    5 #    8 #    done 

but if want print out fibonacci numbers forever? well, pass enumerable returned loop:

fib loop # => 0 #    1 #    ... #    (never stops) 

like said, silly example terrible way generate fibonacci numbers, helps understand there times—albeit perhaps rarely—when it's useful have enumerable never ends, , why loop nice convenience cases.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -