davidhu2000 的评论中已经回答了“为什么”这个问题:
因为您正在打印蓝色之后按字母顺序排列的所有项目
如果你不想使用索引,那么你可以使用带有帮助变量的解决方案:
colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]
blue_found = false
colors.each { |item|
if blue_found
print item
else
blue_found ||= item == "Blue"
end
}
如果你喜欢单线,你可以使用
blue_found ? (print item) : (blue_found ||= item == "Blue" )
另一种可能性:
colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]
blue_found = false
colors.each { |item|
print item if blue_found
blue_found ||= item == "Blue"
}
我很好奇,为什么你不想使用索引,所以我在你的问题之外做了更多的研究。
带有索引的解决方案是:
colors.each_with_index { |item,i|
print item if i > colors.index("Blue")
}
index-方法可能需要更多的运行时间。为了测试它,我做了一个小基准测试:
colors = ["Red", "Blue", "Green", "Purple", "White", "Black"]
require 'benchmark'
TEST_LOOPS = 100_000
def action(item)
#Just a no-action.
end
Benchmark.bm(10) {|b|
b.report('test/variable') {
TEST_LOOPS.times {
blue_found = false
colors.each { |item|
action(item) if blue_found
blue_found ||= item == "Blue"
}
} #Testloops
} #b.report
b.report('test/index') {
TEST_LOOPS.times {
colors.each_with_index { |item,i|
action(item) if i > colors.index("Blue")
}
} #Testloops
} #b.report
b.report('test/index2') {
TEST_LOOPS.times {
index_blue = colors.index("Blue")
colors.each_with_index { |item,i|
action(item) if i > index_blue
}
} #Testloops
} #b.report
b.report('test/dogbert') {
TEST_LOOPS.times {
# Drop all items until you find "Blue", then drop the "Blue".
colors.drop_while { |item| item != "Blue" }.drop(1).each do |item|
action(item)
end
} #Testloops
} #b.report
b.report('test/pjs') {
TEST_LOOPS.times {
after_blue = colors.dup
loop do
break if after_blue.shift == 'Blue'|| after_blue.length < 1
end
after_blue.each{|item| action(item) }
} #Testloops
} #b.report
} #Benchmark
结果:
user system total real
test/variable 0.187000 0.000000 0.187000 ( 0.179010)
test/index 0.250000 0.000000 0.250000 ( 0.254015)
test/index2 0.140000 0.000000 0.140000 ( 0.136008)
test/dogbert 0.110000 0.000000 0.110000 ( 0.111006)
test/pjs 0.327000 0.000000 0.327000 ( 0.332019)
因此,带有帮助变量的版本(如预期的那样)更快。但是如果你在循环之外定义了索引,那么使用索引 (test/index2) 的解决方案几乎和 test/variable 一样快。
免责声明:对于更快的解决方案,我没有太多想法。所以也许有更有效的方法。感谢 dogbert 的提示。