如何使用方法大写来大写字符串数组中的第一个字母?

时间:2013-09-08 00:59:19

标签: ruby arrays methods capitalization

我创建了一个简单的程序,向体育迷询问一些信息。这是我到目前为止的代码:

puts "What's your favorite pro sport?"
favorite_sport = gets.chomp

puts "Who's your favorite team in the #{favorite_sport}?"
favorite_team = gets.chomp

puts "What city are they from?"
team_city = gets.chomp

puts "Who's your favorite player in the #{favorite_team} roster?"
favorite_player = gets.chomp

puts "What position does #{favorite_player} play?"
player_position = gets.chomp

puts "How many years has #{favorite_player} played in the #{favorite_sport}"
years_experience = gets.chomp

fan_info = [favorite_sport, favorite_team, team_city, favorite_player, player_position, years_experience]
puts fan_info

我想让程序输出fan_info,字符串的第一个字母大写。我该怎么做呢?我知道我必须使用方法capitalize,但我无法实现这一点。

以下是输入和输出的示例:

What's your favorite pro sport?
NFL
Who's your favorite team in the NFL?
Seahawks
What city are they from?
seattle
Who's your favorite player in the Seahawks roster?
wilson
What position does wilson play?
qb
How many years has wilson played in the NFL
1
NFL
Seahawks
seattle
wilson
qb
1

2 个答案:

答案 0 :(得分:3)

试试这个:

puts fan_info.map(&:capitalize)

这会在每个字符串上调用#capitalize,构建一个包含所有结果的新数组,然后将其打印出来。

这相当于这样的事情:

fan_info_capitalized = []
fan_info.each do |inf|
  fan_info_capitalized << inf.capitalize
end
puts fan_info_capitalized

只有更紧凑。

答案 1 :(得分:2)

如果你打算将第一个字母大写,保持其他字母不变(即"NFL"保持"NFL",而不是"Nfl"),那么:

favorite_sport = gets.chomp.sub(/./, &:upcase)
...