Example 1: Basic times loop
5.times do puts "Hello, world!" end Output : Hello, world! Hello, world! Hello, world! Hello, world! Hello, world!
In this example, the program uses a times loop to print the message "Hello, world!" five times.
Example 2: Using times loop with a block variable
5.times do |i| puts "The current number is #{i+1}." end Output: The current number is 1. The current number is 2. The current number is 3. The current number is 4. The current number is 5.
In this example, the program uses a times loop with a block variable to print a message that includes the current loop index plus one.
Example 3: Using times loop with a method call
5.times do puts Time.now sleep(1) end Output: 2023-03-20 15:40:27 +0530 2023-03-20 15:40:28 +0530 2023-03-20 15:40:29 +0530 2023-03-20 15:40:30 +0530 2023-03-20 15:40:31 +0530
In this example, the program uses a times loop to print the current time and then wait for one second before printing the next time.
Example 4: Using times loop to fill an array
numbers = [] 10.times do |i| numbers << i * 2 end puts numbers.inspect Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In this example, the program uses a times loop with a block variable to fill an empty array with the first 10 even numbers, and then prints the resulting array.
Example 5: Using times loop with a method call and conditional
5.times do |i| if i.even? puts "#{i} is even." else puts "#{i} is odd." end end Output: 0 is even. 1 is odd. 2 is even. 3 is odd. 4 is even.
In this example, the program uses a times loop with a block variable to print a message for each loop index that indicates whether the number is even or odd, using a conditional statement to determine the output.
0 Comments