Eric Dauenhauer
Eric Dauenhauer

Reputation: 759

Default value for a block argument

I would like to create a method which accepts a block argument but defaults the block to a method that always returns true.

def my_method(&print_if = Proc.new { true })
  internal_value = [1, 2, 3]
  puts "printing" if print_if.call(internal_value)
end

my_method { |array| array[1] == 2 }
 "printing"
 => nil
my_method { |array| array[1] == 3 }
 => nil
my_method
 "printing"
 => nil

It seems that my best option is to check for the presence of a block in the method. This works, its just clunkier

def my_method(&print_if)
  internal_value = [1, 2, 3]
  puts "printing" if !block_given? || print_if.call(internal_value)
end

my_method { |array| array[1] == 2 }
 "printing"
 => nil
my_method { |array| array[1] == 3 }
 => nil
my_method
 "printing"
 => nil

Any way to default a block arg in Ruby? Please no answers that rely on external libraries (even Rails), just trying to find out if this is possible with pure Ruby.

Upvotes: 1

Views: 776

Answers (1)

Dmitriy Pankratov
Dmitriy Pankratov

Reputation: 206

You may use this dirty hack:

def my_method(print_if = -> (*args) { block_given? ? yield(*args) : true })
  internal_value = [1, 2, 3]
  puts "printing" if print_if.call(internal_value)
end

But is it convenient?

Upvotes: 1

Related Questions