gpt4 book ai didi

arrays - 如何在 Ruby 中的数组上使用 for 循环

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

我需要使用 for 循环从 more_stuff 数组中取出最后四个字符串。

这是我的代码:

# assigns string Apples Oranges Crows Telephone Light Sugar to variable 
ten_things
ten_things = "Apples Oranges Crows Telephone Light Sugar"

# prints Wait there are not ten things on that list. Let's fix that.
puts "Wait there are not 10 things in that list. Let's fix that."

# first seperates string ten_things into an array at space character, then
# assigns the new array to variable stuff
stuff = ten_things.split(' ')
# assigns array to more stuff with strings, Day, Night, Song, Frisbee, Girl,
# and Boy
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl",
"Boy"]

# using math to make sure there's 10 items

# assigns fifth through eighth elements in array more_stuff to array stuff_3
stuff_3 = more_stuff[4..8]
# prints array stuff_3 in brackets
puts "#{stuff_3}"
# for all strings in stuff_3
stuff_3.each do |stuff_3|
# pops the last item off of stuff_3
next_one = stuff_3.pop
# puts adding (next_one)
puts "Adding #{next_one}"
# adds (next_one) to array stuff
stuff.push(next_one)
# ends for loop
end

此外,这是我从 Powershell 运行它时出现的错误:

Wait there are not 10 things in that list. Let's fix that.
["Corn", "Banana", "Girl", "Boy"]
ex38for.rb:17:in `block in <main>': undefined method `pop' for "Corn":String
(NoMethodError)
from ex38for.rb:16:in `each'
from ex38for.rb:16:in `<main>'

我对 for 循环的工作方式感到困惑,特别是 each 以及在数组命令中放置内容的位置。

最佳答案

pop 的作用是获取数组的最后一个元素或值(当使用时未指定元素数):

p stuff_3.pop
# => "Boy"
p stuff_3.pop(2)
# => ["Banana", "Girl"]

但在您的情况下,您正尝试将 pop 与主数组内的元素一起使用。

如果您在 each 方法之外检查它:

puts stuff_3.pop
# => Boy

然后将打印 Boy,因为它是 stuff_3 数组中的最后一个元素,您将其声明为 more_stuff[4..8]:

stuff_3 = more_stuff[4..8]
p stuff_3
# => ["Corn", "Banana", "Girl", "Boy"]

但是,当您执行 stuff_3.each do |stuff_3| 时,您使用相同的名称 stuff_3 来访问该数组中的每个元素,该数组具有相同的姓名。所以你会得到 undefined method 'pop' for "Corn":String 错误,因为 pop 正在等待 array 并且如果您遍历 stuff_3 中的每个元素,您将获得 String 元素。

一个可能的解决方案是,当您将 eachstuff_3 数组一起使用时,您可以使用不同的名称来访问元素,也许就像 stuffs,这将为您提供“Adding Boy”和“Adding Girl”。

或者任何引用 stuff_3 中的元素的词都可以与这个不同,因为你没有访问这些元素,你也可以使用 _ 来指定它们未被使用:

stuff_3.each do |_|
next_one = stuff_3.pop
puts "Adding #{next_one}"
stuff.push(next_one)
end

在推送元素之前,这将是stuff:

["Apples", "Oranges", "Crows", "Telephone", "Light", "Sugar"]

之后:

["Apples", "Oranges", "Crows", "Telephone", "Light", "Sugar", "Boy", "Girl"]

关于arrays - 如何在 Ruby 中的数组上使用 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44052994/

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