Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 326
Weston Ganger Avatar asked Mar 01 '16 15:03

Weston Ganger


People also ask

How do you make a loop in Ruby?

The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...

Can you use brackets in Ruby?

Nope. You need to use end instead of a } .

How do you break out of a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

Is there for loop in Ruby?

“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers.


2 Answers

What about this one:

x = 0
x += 1 while x < 5
x 
#=> 5
like image 185
spickermann Avatar answered Sep 22 '22 20:09

spickermann


Instead of this:

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

you could write this:

5.times { |i| puts i }
like image 44
Sagar Pandya Avatar answered Sep 19 '22 20:09

Sagar Pandya