我如何像使用.map一样从数组中提取值?这是我的代码:
counter = 0
ary = Array.new
puts "How many teams do you have to enter?"
hm = gets.to_i
until counter == hm do
puts "Team City"
city = gets.chomp
puts "Team Name"
team = gets.chomp
ary.push([city, team])
counter += 1
end
ary.map { |x, y|
puts "City: #{x} | Team: #{y}"
}
print "The last team entered was: "
ary.last
最终结果如下所示:
City: Boston | Team: Bruins
City: Toronto | Team: Maple Leafs
The last team entered was:
=> ["Toronto", "Maple Leafs"]
但是我要最后一行读
The last team entered was: Toronto Maple Leafs
如何在没有=>,方括号和引号的那一行获取值?
当您不希望在行尾使用换行符时,例如在获取用户输入时,请使用print而不是puts;此外,您还可以#{variable}
使用puts在同一行中进行打印:
counter = 0
ary = Array.new
print "How many teams do you have to enter? "
hm = gets.to_i
until counter == hm do
print "Team #{counter + 1} City: "
city = gets.chomp
print "Team #{counter + 1} Name: "
team = gets.chomp
ary.push([city, team])
counter += 1
end
ary.map { |x, y| puts "City: #{x} | Team: #{y}" }
puts "The last team entered was: #{ary.last.join(' ')}"
用法示例:
How many teams do you have to enter? 2
Team 1 City: Boston
Team 1 Name: Bruins
Team 2 City: Toronto
Team 2 Name: Maple Leafs
City: Boston | Team: Bruins
City: Toronto | Team: Maple Leafs
The last team entered was: Toronto Maple Leafs
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句