Using block-reference instead of yield + block_given?

Using block-reference instead of yield + block_given?

Share it now. It takes only a few seconds! 😉


Use block-reference instead of yield + block_given?

Using each + yield

class Instructions < Array
  def process
    return self.to_enum unless block_given?

    self.each do |instruction|
      yield(instruction)
    end
  end
end

instructions = Instructions.new(%I(instruction1 instruction2))

instructions.process { |instruction| pp instruction } # => list instructions
instructions.process                                  # => #<Enumerator: ...>

Using block references

class Instructions < Array
  def process(&block) = self.each(&block)
end

instructions = Instructions.new(%I(instruction1 instruction2))

instructions.process { |instruction| pp instruction } # => list instructions
instructions.process                                  # => #<Enumerator: ...>

We're also available on