gpt4 book ai didi

ruby - 从方法执行下一个

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

这段代码:

def skip_if_three(count)
puts 'three detected, let\'s skip this loop!' if count == 3
end

5.times do |count|
skip_if_three(count)
puts count
end

返回:

0
1
2
three detected, let's skip this loop!
3 # don't want this to appear!
4

但是,如果使用下一个关键字并执行此操作:

def skip_if_three(count)
next if count == 3
end

5.times do |count|
skip_if_three(count)
puts count
end

我得到这个语法错误:

Invalid next

这在意料之中。但是如何使用助手的 next 呢?

更新

我正在使用嵌套循环并且需要在每个循环中执行我的检查,所以我想保持它干燥,因此使用外部方法。

5.times do |i|
skip_if_three(i)
puts count

5.times do |j|
skip_if_three(j)
puts count
end
end

最佳答案

def skip_if_three(count)
return unless count == 3
puts "three detected, let's skip this loop!"
throw(:three)
end

5.times do |count|
catch(:three) do
skip_if_three(count)
puts count
end
end

结果:

0
1
2
three detected, let's skip this loop!
4

def three?(count)
return unless count == 3
puts "three detected, let's skip this loop!"
true
end

5.times do |count|
puts count unless three?(count)
end

结果:

0
1
2
three detected, let's skip this loop!
4

def three?(count)
return unless count == 3
puts "three detected, let's skip this loop!"
true
end

5.times do |count|
next if three?(count)
puts count
end

结果:

0
1
2
three detected, let's skip this loop!
4

关于ruby - 从方法执行下一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24793822/

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