如何从数组中提取值,就像使用.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
如何在没有=>,括号和引号的情况下获取该行的值?
答案 0 :(得分:3)
基本上,你提出的问题是“如何将字符串数组元素连接成一个字符串”,Array#join
来拯救:
["Toronto", "Maple Leafs"].join(' ')
#⇒ "Toronto Maple Leafs"
答案 1 :(得分:1)
使用*
的替代方法:
puts ["Toronto", "Maple Leafs"] * ', '
#Toronto, Maple Leafs
#=> nil
但我认为没有人使用这种表示法,因此在另一个答案中建议使用join
。
答案 2 :(得分:0)
如果您不想在行尾添加换行符,例如获取用户输入时,请使用print代替puts,此外,您还可以使用__cdecl
在同一行内打印提出:
#{variable}
使用示例:
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(' ')}"
试试here!
答案 3 :(得分:0)
试一试:
team_last = ary.last
puts "The last team entered was:" + team_last[0] + team_last[1]
答案 4 :(得分:0)
根据你的代码ary.last
本身返回一个数组,所以首先需要通过ary.last.join(' ')
连接数组中的两个元素将其转换为字符串,然后你必须用您的消息字符串即"The last team entered was: #{ary.last.join(' ')}"
代码的最后两行将更改为:
print "The last team entered was: #{ary.last.join(' ')}"