如何获取Ruby中数组的最后一个元素?

ComputerUser5243

我如何像使用.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

如何在没有=>,方括号和引号的那一行获取值?

萨什·辛哈(Sash Sinha)

当您不希望在行尾使用换行符时,例如在获取用户输入时,请使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在二维数组ruby中打印子数组的最后一个元素

如何使用解构获取数组的最后一个元素

如何获取数组中的下一个和上一个元素,Ruby

获取Bash数组中的最后一个元素

从数组中获取每个元素的最后一个

获取数组的最后一个元素?

如何在邮递员中获取json数组中的最后一个元素

如何使用golang获取mongodb中数组中的最后一个元素?

如何获取MySQL JSON数组中的最后一个元素?

如何在Swift中获取数组的最后一个元素?

如何获取猫鼬的数据在数组中的最后一个元素?

如何在Smarty模板中获取数组的最后一个元素

如何删除bash中数组的最后一个元素?

如何获取PostgreSQL文本中的最后一个元素?

在hadoop中,如何获取值的最后一个元素

在javascript数组中,如何获取除第一个元素以外的最后5个元素?

如何获取数组中的最后一个键?

如何检测一个元素是否是数组中的最后一个元素?

如何获取数组中的下几个元素,但在传递最后一个元素时跳回到开头?

如何仅返回数组的最后一个元素而不获取所有元素

如何获取数组的最后一个元素并显示其余元素?

仅获取数组猫鼬的最后一个元素

Haxe获取数组的最后一个元素

获取数组每个元素的最后一个维度

获取json数组中元素的最后一个索引

如何获取字符串数组列表的最后一个元素?

设置条件时如何获取最后一个元素数组(删除重复数据)

解构以获取es6中数组的最后一个元素

Laravel php 获取多维数组中的最后一个元素