Ruby sample scripts - Looping constructs

loop1.rb

#!/usr/bin/env ruby
for x in 1..10
   puts "Counting " + x.to_s
end

loop2.rb
#!/usr/bin/env ruby
for x in 1...10
   puts "Counting " + x.to_s
end

loop3.rb
#!/usr/bin/env ruby
10.times do |i|
   puts "Counting #{i}"
end


loop4.rb
#!/usr/bin/env ruby
(1..10).each {|i| puts "Counting #{i}" }


loop5.rb
#!/usr/bin/env ruby
1.upto(10) {|i| puts "Counting #{i}" }

loop6.rb
#!/usr/bin/env ruby
# Checking whether a number is prime can be
# much simpler than this. But this example demonstrates
# loop construct and duck-typing.

# A simple duck-typing example. 
# Add a new method/functionality to an existing class
class Fixnum
    def is_prime? 
        (2..Math.sqrt(self).floor).each {|x| return false if self % x == 0 }
        return true
    end
end
 

loop do 
   print "Enter a number (0 to exit): "
   num = gets.to_i
   break if num == 0
   puts "#{num} is" + (num.is_prime? ? " " : " NOT ") + "prime."
end


loop7.rb

puts "Ho! Ho! Ho!" while (Time.now.min == 15)

#while (Time.now.min == 15) 
#    puts "Ho! Ho! Ho!"
#end


num1.rb
#!/usr/bin/env ruby
10.times do
   puts "Hello"
end

num2.rb
#!/usr/bin/env ruby
10.times do |x|
   puts "Counting " + x.to_s
end

Tags: