The hidden power of ruby’s “next” keyword

Note: This is not part of the lottery programming project! Don’t freak out if none of these make any sense to you!

Most ruby programmers have used the next keyword in iterators like Array#each. For example…

[2, 2, 8, 4, 5, 7, 3, 8, 5, 5].each do |e|
  next if e.even?
  puts e
end

Pretty straight forward stuff here. But what you probably don’t know is that you can pass an argument to next and it would be passed back to the method that yield-ed the block. For example:

def my_method
  puts yield
end

my_method { next 'Hello World' } # => 'Hello World'

Now, I agree that this might not be the a particularly interesting example, since the last statement will automatically become the return value of yield even without the next. However, this could be very useful in some case:

class MagneticTapeReader
  def initialize
    @pointer = 0
  end

  def each_byte
    rtn = yield read(@pointer)

    if rtn.nil?
      @pointer += 1
    else
      @pointer += rtn
    end
  end
end

m = MagneticTapeReader.new

m.each_byte do |byte|
  if byte < 0x20
    next 8 # Skip ahead 8 bytes
  else
    puts byte.chr
  end
end

It’s also extremely useful when you’re writing generators of some sort. For example, if you are writing a permutation generator, it might be useful to allow the caller of your method to skip several permutations, or better yet, skip to a certain permutation.

Another note of interest is that this also works for the break keyword.

One Response to “The hidden power of ruby’s “next” keyword”

  1. [...] by godfreychan on 2010/01/29 Just blogged about this on my blog today, which might be of interest to the MarkUs [...]

Leave a Reply