在 Ruby 中使用 gets 命令按字母顺序对数组进行排序

发布于 2024-11-02 21:54:16 字数 265 浏览 0 评论 0原文

我是一个 Ruby 菜鸟,我只是尝试使用 gets 命令对单词数组(“dog”、“cat”、“ape”)进行排序,应该通过 gets 单独输入并成为(“ape”、“cat”、 “狗”)

我已经尝试过:

list = Object.new
list = []
word = STDIN.gets
list.push(word)
$/ = "END"
puts list

任何帮助都会很棒,因为这可以帮助我女儿更快地整理作业并学习打字。

I am a Ruby noob and am simply trying to use the gets command to sort a array of words ("dog", "cat", "ape") should be entered individually by gets and become ("ape", "cat", "dog")

I have tried:

list = Object.new
list = []
word = STDIN.gets
list.push(word)
$/ = "END"
puts list

Any help would be great as this is to help my daughter sort her homework faster and learn to type.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野生奥特曼 2024-11-09 21:54:16

如果您愿意,您也可以一次输入所有单词:

>> words = gets.chomp.split(/,\s*/).sort
dog, cat,ape                             #=> ["ape", "cat", "dog"]

如果您想单独阅读它们:

>> words = [] #=> []
>> until (word = gets.chomp).empty? do
..     words << word
..   end
cat
ape
dog
         #=> nil
>> words.sort #=> ["ape", "cat", "dog"]

这只是从 IRB 复制/粘贴,但很容易制作成您想要的程序。

You can also enter all the words at once if you want to:

>> words = gets.chomp.split(/,\s*/).sort
dog, cat,ape                             #=> ["ape", "cat", "dog"]

If you want to read them individually:

>> words = [] #=> []
>> until (word = gets.chomp).empty? do
..     words << word
..   end
cat
ape
dog
         #=> nil
>> words.sort #=> ["ape", "cat", "dog"]

That's just copy/paste from IRB, but easy enough to make into the program you want.

初吻给了烟 2024-11-09 21:54:16
list = []
until (word = gets.chomp) == "END"  do
  list << word
end

puts "Sorted Values:"
puts list.sort

这将接受输入,直到您给出“END”(您可以根据需要更改它)。

我正在调用 Array#sort

list = []
until (word = gets.chomp) == "END"  do
  list << word
end

puts "Sorted Values:"
puts list.sort

This will take input until you give it "END" (you can change this as you wish).

I am calling Array#sort

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文