gpt4 book ai didi

ruby - 交替大写和小写 ruby

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:45 26 4
gpt4 key购买 nike

我是 Ruby 的新手,想知道如何自动生成一个空数组来显示输入的数据以按字母顺序排序,并在大写和小写之间交替输入每个条目。我在这个网站上看到过类似的帖子,描述了如何实现这一点,但似乎无法让它发挥作用。

下面是我的代码,这里使用的是示例:How to have the user input alternate between uppercase and lowercase in Ruby?

目前我的代码首先交替大小写,然后按字母顺序排序(创建两个列表)。我想要的只是一个按字母顺序排列并交替大小写的列表。我希望这是有道理的,谢谢你的时间!

puts "Welcome to the word list!"

words = []

5.times do
puts "Please enter a word:"
words << gets.chomp
end

words.each_with_index do |word, index|
if index.even?
puts word.upcase
else
puts word.downcase
end
end

puts "Here are your words:"
puts words.sort

最佳答案

首先,在这两种情况下你会得到不同的结果:

 1. sort the words first and then apply your alternate upcase/downcase logic.
2. apply your alternate upcase/downcase logic first, then sort the words.

因为如果先对单词进行排序,单词在原始输入数组中的索引将会改变。因此,当您根据输入数组中单词的索引执行此操作时,它会对您的大写/小写逻辑产生影响。

所以,先排序还是后排序,看你原来的需求了。

这是第一种方法:

puts "Welcome to the word list!"

words = []
results = []

5.times do
puts "Please enter a word:"
words << gets.chomp
end

words.sort.each_with_index do |word, index| # sort the input words first, then loop through
# accumulate the results in the results array
if index.even?
results << word.upcase
else
results << word.downcase
end
end

puts "Here are your resulting words: "
puts results

如果你想要第二个,你可以在最后排序。

关于ruby - 交替大写和小写 ruby ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600299/

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