4
\$\begingroup\$

I do not like to use 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 < 10000
 puts value = value**2
end
# => 4
# 16
# 256
# 65536

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 27, 2014 at 22:26
\$\endgroup\$
1
  • \$\begingroup\$ You could also write, value = 2; loop do; break if value >= 10_000; puts value = value**2; end. \$\endgroup\$ Commented Jul 29, 2014 at 5:18

2 Answers 2

4
\$\begingroup\$

Using 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 it

puts value = value**2 while value < 10000

or use until if you want, but same difference

puts value = value**2 until value >= 10000

If 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
end

but the whole point here is really that you don't know the number of iterations.

answered Jul 27, 2014 at 23:23
\$\endgroup\$
-1
\$\begingroup\$

I see nothing wrong in using the while word since your function logically is doing smth while ...
Wolfram Mathematica has NestWhile, that can be implemented in Ruby like this:

def nest_while f, expr, test
 expr = f[expr] while test[expr]
end
nest_while ->i{ (i**2).tap &method(:puts) }, 2, ->i{ i<10000 }
4
16
256
65536
=> nil

Also you might be interested in implementing NestWhileList: using yield like at SO: Are there something like Python generators in Ruby?. .

answered Jul 29, 2014 at 9:51
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.