1

What happens if you use a method that has a yield, without passing a block to it?

class SomeClass < Array
    def some_method
        yield(self[i])
    end
end

a = SomeClass.new
a.some_method

And is there a way to set a default behavior: give to the method default block to run, if other is not given?

OlehZiniak
  • 933
  • 1
  • 13
  • 29

1 Answers1

4

You can use Kernel#block_given? to determine if a block is passed and take the appropriate action.

class SomeClass < Array
  def some_method
    if block_given?
      yield(self[i])
    else
      # not given
    end
  end
end

That means you can also have a default action if the block is not passed.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364