【发布时间】:2017-05-18 16:15:48
【问题描述】:
我需要使用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 以及在数组命令中放置内容的位置。
【问题讨论】: