gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:23 25 4
gpt4 key购买 nike

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

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

最佳答案

试试这个:

puts fan_info.map(&:capitalize)

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

它等同于这样的东西:

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

只是更紧凑。

关于ruby - 如何使用 capitalize 方法将字符串数组中的第一个字母大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com