Question

I want to make a program like,ask a number and print 1 to number by using gets and by using loop. So,I am asking about gets and how to do program which is I given below as program title.

How to ask a number by using gets?If possible explain me with example.

By using gets,I want to print 1 to number. My program titleis Ask a number and print 1 to number by using Ruby.

How can I solve that program?Please help me on this.

Was it helpful?

Solution

As Arup, suggested use Kernel#gets to capture a user input from terminal. The remaining bit can be simply done with a for loop:

num = gets.to_i                    #Convert the user input to integer

for i in 1..num
  puts i
end

You can further modify this to suit your need.

OTHER TIPS

Do as below using Kernel#gets. #gets will give you a string, then to convert the number string to a number use String#to_i.

number = gets.to_i

If I want to make program which from 1 to number then what should I do?

Use a Range then.

(1..number).each do |n|
   # code
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top