2017-02-18 134 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(' ')}" 
相關問題