1

I'm trying to get multiple inputs and assign it to different variables (in the irb) but I can't seem to get it to work. I'm only able to do it for the first variable, but for the next three, the last input gets assigned to the other 2 (I have 4 in all)

What I'm trying to do is, based on the first input (say, 2), it'll prompt for 3 more inputs 2 times.

t = gets.to_i

This is the first input and it gets assigned properly. It'll then prompt for 3 more inputs, but then only the last input gets saved and is assigned to all three variables.

a = gets.to_i
b = gets.to_i
k = gets.to_i

it'll accept 3 inputs but only the last gets saved?

say if I enter (for the first iteration)

1
10
3

after the first prompt (which i entered 2) a, b, and k has value 3

t = gets.to_i
a = b = k = []

for i in 0..t-1 do
  a[i] = gets.to_i
  b[i] = gets.to_i
  k[i] = gets.to_i
end

Is it because it's in a loop? I'm putting it there since it has to ask for the values of a, b and k for t times where t is the first input.

I'm not sure if I explained it properly but I hope someone can understand what I was trying to do

2
  • Hint: how many arrays do you create in your code? There are two ways to create an array, using an array literal (e.g. []) or by calling one of the Array factory methods (e.g. Array::[] or Array::new). Count the number of calls to factory methods and count the number of array literals in your code. Commented Mar 26, 2017 at 12:15
  • @JörgWMittag I see it now. Thank you!! (esp for not answering it explicitly) :) I appreciated it. Commented Mar 26, 2017 at 23:14

1 Answer 1

2

The only way to address a variable in Ruby is by reference. That said,

a = b = k = []

declares three references to the same object. To fix it, declare arrays separately:

t = gets.to_i
a, b, k = [], [], []

for i in 0..t-1 do
  a[i] = gets.to_i
  b[i] = gets.to_i
  k[i] = gets.to_i
end

Sidenote: for loop is not ruby idiomatic. Use e. g. Range#each instead (or Integer#upto):

(0...t).each do |i| # or 0.upto(t - 1) do |i|
  a[i] = gets.to_i
  b[i] = gets.to_i
  k[i] = gets.to_i
end
Sign up to request clarification or add additional context in comments.

Comments

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.