Skip to main content
Ruby

RUBY – Getting a little LOOPY with UPTO

By October 14, 2013No Comments



It is often the case that we need to loop through tasks a certain amount of times. In other languages you may use a for loop for this but in ruby we can use the upto method or, for counting down, there is downto. Consider the example in the following script:

#!/usr/bin/ruby
print "How many time to you want to do this? "
count = gets.chomp.to_i
1.upto(count) do | x |
  puts "Creating user#{ x }"
end

Firstly we can streamline the to_i casting method on to the end of chomp. This then casts the input string to an integer. We then start at 1 and then we use the upto method to reach the maximum tries we specified in our count variable. We enter the do block and we choose to use the iterator x to accompany us into the loop. As you can see we then print out a message about creating user1, user2 etc. Sure we are not creating users but in another example we will soon using code similar to this.