while and until in Ruby

Using while and until:

1.upto(5) { |raveendran| puts raveendran}

output:

1
2
3
4
5

However, it’s possible to loop code in other ways. while and until allow you to loop
code based on the result of a comparison made on each loop:

x = 1
while x < 100
puts x
x = x * 2
end

output:
1
2
4
8
16
32
64

The same output using UNTIL:

x = 1
until x > 99
puts x
x = x * 2
end

It’s also possible to use while and until in a single line setting, as with if and unless:
i = 1
i = i * 2 until i > 1000
puts i
output:

1024

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s