从方法执行下一步

时间:2014-07-17 02:16:42

标签: ruby

此代码:

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

我得到这个SyntaxError:

  

无效的下一步

这是预期的。但是如何使用帮助器中的next

更新

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

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

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

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

更好的解决方案是重新设计代码块,以便您不会遇到此问题。像next这样的隐藏功能并不理想,所以像这样的东西会保留你的模型代码的简洁性,同时明确实际发生的事情:

def is_three? count
  count == 3
end

5.times do |count|
  next if is_three? count
  puts count
end