patternrubyMinor
Generating sequence that uses the previous outcome for the current
Viewed 0 times
theprevioususessequencegeneratingoutcomethatforcurrent
Problem
I do not like to use
I have a suspicion that there is a way/method to do this, but I do not know which one. I hope someone can point me in the right direction.
while loops in Ruby. I was wondering how I can generate a "squared sequence" (e.g., squares the first input, then squares the outcome, etc.) in a more idiomatic Ruby way than this one:value = 2
while value 4
# 16
# 256
# 65536I have a suspicion that there is a way/method to do this, but I do not know which one. I hope someone can point me in the right direction.
Solution
Using
You can postfix the
or use
If you were dealing with a fixed or known number of iterations, you could do something like
but the whole point here is really that you don't know the number of iterations.
while would be idiomatic in almost any language. while is basically the way to iterate, uh, while a condition is true. Hence the name - it's practically plain English.You can postfix the
while and save a couple of lines, but that's about itputs value = value**2 while value < 10000or use
until if you want, but same differenceputs value = value**2 until value >= 10000If you were dealing with a fixed or known number of iterations, you could do something like
4.times.inject(2) do |memo, _|
puts memo = memo ** 2
memo
endbut the whole point here is really that you don't know the number of iterations.
Code Snippets
puts value = value**2 while value < 10000puts value = value**2 until value >= 100004.times.inject(2) do |memo, _|
puts memo = memo ** 2
memo
endContext
StackExchange Code Review Q#58223, answer score: 4
Revisions (0)
No revisions yet.