Ruby Integer times function with example

The times function in Ruby returns all the numbers from 0 to number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.

Syntax: (number).times

Parameter: The function takes the integer till which the numbers are returned. It also takes an block.



Return Value: The function returns all the numbers from 0 to number itself.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for times function 
   
# Initializing the number 
num1 = 8
   
# Prints the number from 0 to num1 
puts num1.times { |i| print i, " " }
    
# Initializing the number
num2 = 5
   
# Prints the number from 0 to num2
puts num2.times { |i| print i, " " }

chevron_right


Output :

0 1 2 3 4 5 6 7 8
0 1 2 3 4 5

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for times function 
   
# Initializing the number 
num1 = 4
   
# Prints the number from 0 to num1 
puts num1.times { |i| print i, " " }
   
# Initializing the number
num2 = -2
   
# Prints the number from 0 to num2
puts num2.times { |i| print i, " " }

chevron_right


Output:

0 1 2 3 4
-2

Example #3:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for times function 
   
# Initializing the number
num1 = 5
   
# Prints enumerator as no block is given 
puts num1.times 

chevron_right


Output:

#


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.