Saturday, 3 December 2016

Ruby loops examples

Ruby Programming Loops

Ruby also provides different types of loops like  other programming languages does. But its syntax quiet different and also multiple options you can see for the loop constructs.

While and until loops in Ruby


While loop

Ex: Printing 1 to 10 numbers




Ex;2
while
#script to find factorial of a given number

puts "enter the number"
x=gets.chomp.to_i 
fact=1
while x > 0
fact= fact * x
x -= 1
end
puts "the factorial for given number is #{fact}"


Output:

E:\Ruby>ruby factorial.rb
enter the number
5
the factorial for given number is 120


Few challenges were found while executing this script.
factorial.rb:6:in `>': comparison of String with 0 failed (ArgumentError) from factorial.rb:6:in `


 it was troubleshooted by adding "chomp.to_i" method to gets method to convert given number into integer Most important lesson: read the error messages. Ruby failed to compare a number to a string because they are just incompatible data types: it's nonsensical to ask what is bigger: "abc" or 123. And gets.chomp always gives you a String (something like "4", which is not the number 4). So in order to compare the user's input to a number, you have to convert it to a number first: Ruby Strings have the .to_i (to integer) method for this
until

for loop

for
each loop
each do 

  This loop stops execution when condition becomes false

4 comments: