我有一个任务puts
无限数word
,每个都在一行到数组,当在空行上按Enter时,puts
这些单词的顺序相反。如何定义何时按下输入或输入空行?
代码在这里:
word = []
puts "Enter word"
add = 0
until add == ????
word.push gets.chomp
add = word.last
end
puts word.reverse
答案 0 :(得分:1)
这是一个可能的解决方案,带有评论。我没有看到您的add
变量有任何有用的角色,所以我忽略了它。我也相信定期提示用户,以便他们知道程序仍在使用它们,所以我在循环中移动了用户提示。
word = [] # Start with an empty array
# Use loop when the terminating condition isn't known at the beginning
# or end of the repetition, but rather it's determined in the middle
loop do
print 'Enter word: ' # I like to prompt the user each time.
response = gets.chomp # Read the response and clean it up.
break if response.empty? # No response? Time to bail out of the loop!
word << response # Still in the loop? Append the response to the array.
end
puts word.reverse # Now that we're out of the loop, reverse and print
您可能希望也可能不希望使用strip
而不是chomp
。如果用户输入一行空格,条带将停止。
答案 1 :(得分:0)
在这里,这是您的代码的修改版本,它可以按要求运行。
word = []
puts "Enter word"
add = 0
while add != -1
ans = gets.chomp
word.push ans
if ans == ""
puts word.reverse
exit
end
add += 1
end
puts word.reverse
这是另一个版本,使用(正如您最初所做的)直到循环。
word = []
puts "Enter word"
add = 0
until add == Float::INFINITY
ans = gets.chomp
word.push ans
if ans == ""
puts word.reverse
exit
end
add += 1
end
puts word.reverse