2017-02-18 170 views
0

如何从数组中获取数值,就像使用.map一样?这里是我的代码:如何获取Ruby中数组的最后一个元素?

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

使用打印的,而不是看跌期权,当你不想要一个新行不字符在例如线的末端时获取用户输入,此外还可以使用#{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(' ')}" 

实例应用:

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 

试试吧here!

+0

起初我所有“Nawwww我喜欢我的格式”,然后我尝试了你的,哦,是它的wayyyy更好。妈的点燃,fam!我只是在学Ruby,这很棒。谢谢! – ComputerUser5243

+0

'ary.map {| x,y |放置“城市:#{x} |团队:#{y}”}'滥用'map',必须在那里使用'each'迭代器**。 – mudasobwa

3

基本上,你的问题是“如何加入字符串数组元素连接成一个字符串”,并Array#join就派上用场了:

["Toronto", "Maple Leafs"].join(' ') 
#⇒ "Toronto Maple Leafs" 
0

试试:

team_last = ary.last 
puts "The last team entered was:" + team_last[0] + team_last[1] 
+0

你有没有读过一个问题,或者你直接回答标题? – mudasobwa

+0

噢,对不起。我希望这可以帮助 – Reckordp

+0

这不是一个正确的红宝石代码。 – mudasobwa

1

的另一种方式与*

puts ["Toronto", "Maple Leafs"] * ', ' 
#Toronto, Maple Leafs 
#=> nil 

但我不认为任何人使用这个符号,从而在另一个答案中推荐使用join

0

根据你的代码ary.last本身返回数组所以首先你需要通过ary.last.join(' ')加入数组中的两个元素,将其转换为字符串,然后你将与你的消息字符串插值它即"The last team entered was: #{ary.last.join(' ')}"

代码的最后两行会改变为:

print "The last team entered was: #{ary.last.join(' ')}" 
相关问题