我有一些Ruby练习,我有输入问题。 我想知道如何在1行中输入M值,空格介于2个值之间, 并做那样的N行。 有谁可以帮助我?请!
答案 0 :(得分:1)
如果您想获得用户输入,那么您可以考虑使用gets
,这样:
# a stores what the user introduces, in this case "a b c"
a = gets.chomp
# => "a b c"
例如,如果您希望允许用户输入多个值(由空格或任何其他值分隔),则可以使用split
,如:
# in this case split without arguments takes the input as string, and divides it within every whitespace ang gives you them in an array.
a = gets.chomp.split
=> ["a", "b", "c"]
然后,您已经可以在1行中获取 M值的用户输入,其中2个值之间的空格。如果您想重复此操作,那么您可以使用times
,指定您希望这样做的次数,即:
# This will store what the user introduces, splitted as before, and each array will be inside a "main" array.
# If for instance the input is 1 2 3 the first time, a b c the second time, then you get
a = 2.times.map do
gets.chomp.split
end
p a
# => [["1", "2", "3"], ["a", "b", "c"]]