2

How can I build an Array with multiple values accepted from the user at run time?

For e.g., we have in c++ like:

for(i=0;i<10;i++){ cin>>a[i]; }

3 Answers 3

5

Like this:

Array.new(10){gets.chomp}
Sign up to request clarification or add additional context in comments.

Comments

3

You can use gets:

a = []
10.times{|i| a[i] = gets.chomp}

Demonstration

2 Comments

Or just a << gets.chomp
Or a = 10.times.map { gets.chomp }
0

Try this:

a = []
10.times{a.push(gets.chomp)}

1 Comment

The second line, though correct, does not return a. You could write 10.times.map { gets.chomp }, which does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.