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?
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 ...
Nope. You need to use end instead of a } .
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.
“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.
What about this one:
x = 0
x += 1 while x < 5
x
#=> 5
Instead of this:
x = 0
while x < 5 do
puts x
x += 1
end
you could write this:
5.times { |i| puts i }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With