49

I have a method which takes a code block.

def opportunity
  @opportunities += 1
  if yield
    @performances +=1
  end
end

and I call it like this:

opportunity { @some_array.empty? }

But how do I pass it more than one code block so that I could use yield twice, something like this:

def opportunity
  if yield_1
    @opportunities += 1
  end
  if yield_2
    @performances +=1
  end
end

and:

opportunity {@some_other_array.empty?} { @some_array.empty? }

I am aware that this example could be done without yield, but it's just to illustrate.

1 Answer 1

73

You can't pass multiple blocks, per se, but you can pass multiple procs or lambdas:

Using 1.9 syntax:

opportunity ->{ @some_array.empty? }, ->{ @some_other_array.empty? }

and in the method itself:

def opportunity(lambda1, lambda2)
  if lambda1.()
    @opportunities += 1
  end
  if lambda2.()
    @performances += 1
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

Is it other way to declare that functions
Proc.new {} or lambda {} also work. Any object that responds to call will work
Is the method .() an alias of .call ?
@MrYoshiji YES! ruby-doc.org/core-2.2.0/Proc.html#method-i-call " Note that prc.() invokes prc.call() with the parameters given. It’s a syntax sugar to hide “call”."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.