Related Articles

Related Articles

Ruby Integer times function with example
  • Last Updated : 17 Mar, 2020

The times function in Ruby returns all the numbers from 0 to one less than the 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 one less than the 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-1 
puts num1.times { |i| print i, " " }
    
# Initializing the number
num2 = 5
   
# Prints the number from 0 to num2-1
puts num2.times { |i| print i, " " }

chevron_right


Output :

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

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-1 
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
-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
Recommended Articles
Page :