Kostas Andrianos
Kostas Andrianos

Reputation: 1619

What if block_given? returns false?

I have this piece of code, and I want to write a test for it. It is part of an open source project, so I wasn't the one who wrote it. I know that |c| yield c if block_given? will execute the block that is given (if it is), but if not block_given? will return false. What will happen in that case? Thank you for your time.

::CSV
 .open(path, 'rb', opts)
 .tap { |c| yield c if block_given? }
 .to_a

Upvotes: 0

Views: 238

Answers (1)

Adam Zapaśnik
Adam Zapaśnik

Reputation: 683

The simplest way is to check it :)

def block
  (1..10)                .tap {|x| puts "original: #{x.inspect}"}
    .select {|x| x%2==0} .tap {|x| yield x if block_given?}
end
block { |x| puts "evens: #{x.inspect}"}
block

First call returns:

=> original: 1..10
=> evens: [2, 4, 6, 8, 10]

Second call returns:

=> original: 1..10

If there is no block given the yield won't be called, so the empty block is going to be passed to #tap.

Upvotes: 1

Related Questions