我是 Ruby 的新手,我写了一个非常简单的应用程序来打印星期几,然后循环删除一天:
def print_days(days)
days.each do |day|
print "The day of the week is: #{day}\n"
days.delete(day)
print "\n*****************************************************\n"
print days
print "\n*****************************************************\n"
end
end
wd = %w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday]
print print_days(wd
这会在运行时提供以下输出。谁能解释为什么当我按顺序删除每个元素并且数组显示它们在那里时会跳过星期二、星期四和星期六?您可以在您的设置中运行这个简单的代码:
The day of the week is: Monday
*****************************************************
["Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
*****************************************************
The day of the week is: Wednesday
*****************************************************
["Tuesday", "Thursday", "Friday", "Saturday", "Sunday"]
*****************************************************
The day of the week is: Friday
*****************************************************
["Tuesday", "Thursday", "Saturday", "Sunday"]
*****************************************************
The day of the week is: Sunday
*****************************************************
["Tuesday", "Thursday", "Saturday"]
*****************************************************
["Tuesday", "Thursday", "Saturday"]
请您参考如下方法:
您在遍历数组时从数组中删除元素,从而使迭代器无效。
你可以试试
until (days.empty?)
day = days.shift
print "The day of the week is: #{day}\n"
end
或
days.each{|day| print "The day of the week is: #{day}\n"}
days.clear