Weston Ganger
Weston Ganger

Reputation: 6702

How to do a one-liner while loop in Ruby using curly braces

I was trying to do a simple one liner while loop in ruby using the curly braces. I was sucessful in the following formats:

while x < 5 do x+=1 end

This is sufficient as a one liner but im not a fan of using do end in one liners. I would like to do something similar to this:

while x < 5 { x += 1 }

Can this be done?

Upvotes: 13

Views: 7951

Answers (3)

bogl
bogl

Reputation: 1863

If the question is "How to use while with curly braces? Can it be done?", then the answer is: No, it is not possible.

Instead, you could use while without do...end, and without curly braces:

x = 0
(x+=1; p x) while x<5

Or you could use curly braces without while, to achieve the same:

x=0
(x+1..5).each{|y| p y}

Upvotes: 8

Sagar Pandya
Sagar Pandya

Reputation: 9497

Instead of this:

x = 0
while x < 5 do
  puts x
  x += 1
end

you could write this:

5.times { |i| puts i }

Upvotes: 2

spickermann
spickermann

Reputation: 106782

What about this one:

x = 0
x += 1 while x < 5
x 
#=> 5

Upvotes: 20

Related Questions