如何根据用户输入添加到Ruby数组?
问题描述:
我要求用户输入一个数字并根据该数字我想添加某些玩家到我的游戏。如何根据用户输入添加到Ruby数组?
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
所以,如果他们输入3.然后代码应循环3次,并要求用户的名字。例如
What is the players name? Rich
What is the players name? Tom
What is the players name? Charles
话,那就得玩家= [ '富', '汤姆', '查尔斯']
任何想法,为什么我的代码是不正确的? (我想,这是与range
部分也许做)
答
有在你的代码的一些错误:
起初,你所要求的数字,但是players_amount是一个字符串。您应该使用to_i
方法进行转换。
然后,对于遍历一个范围,在Ruby中有几种方法,但在Python中没有关键字range
。对于迭代一个范围(即间隔),使用方法:
# 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
,而不是你的for循环,只写(0...players_amount).each do
所以,。
通过这些修改,程序具有预期的行为。但是,如果要让名称出现在问题的同一行上,请使用print
而不是puts
,因为puts
会在字符串末尾自动添加换行符。
答
我会补充T. Claverie的答案。在这种情况下,我想你只需要迭代一定次数而对迭代索引不做任何事情。这样,我会用您的代码中的for
循环替换如下:
players_amount.times do
puts ('What is the players name')
name = gets.chomp
players.push(name)
end
希望它有帮助。
+0
您仍然需要使用'to_i'将字符串转换为整数。 –
'range'定义在哪里? – Stefan