1

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

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
4

2 回答 2

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

只有更紧凑。

于 2013-09-08T01:17:00.993 回答
2

如果您的意图是将第一个字母大写以保持其他字母不变(即"NFL"保持为"NFL",而不是"Nfl"),则执行以下操作:

favorite_sport = gets.chomp.sub(/./, &:upcase)
...
于 2013-09-08T02:09:03.580 回答