hellogoodbye hellogoodbye - 6 months ago 11
Ruby Question

How do you add to a Ruby array based on users input?

I am asking the user to input a number and based on that number I want to add certain players to my game.

class Player
def players_playing
players = []
puts('How many players are playing?')
players_amount = gets.chomp
for i in range(players_amount)
puts ('What is the players name')
name = gets.chomp
players.push(name)
end
end
end


So if they enter 3. Then the code should loop through 3 times and ask the user for names. e.g.

What is the players name? Rich
What is the players name? Tom
What is the players name? Charles


Then it would have players = ['Rich', 'Tom', 'Charles']

any ideas why my code is not correct? ( i figure it is to do with the
range
part maybe)

Answer

There are some mistakes in your code:

At first you are asking for a number, however players_amount is a string. You should convert it using the to_i method.

Then, for iterating over a range, there are several ways of doing it in Ruby, but there is no keyword range as in Python. For iterating over a range (that is, an interval), use:

# Exclusive: 

(0...3).each do |i|
    puts i
end
# 0
# 1
# 2

# Inclusive:

(0..3).each do |i|
    puts i
end
# 0
# 1
# 2
# 3

So, instead of your for loop, just write (0...players_amount).each do.

With those modifications, the program has the expected behaviour. However, if you want the name to appear on the same line of the question, use print instead of puts because puts adds automatically a line break at the end of the string.

Comments