Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby syntax for passing block [duplicate]

Tags:

ruby

Why syntax with curly braces works as expected:

class SomeClass
  include Parser::Http.new { |agent|
    # PASSED: This block was passed to Http::new
  }
end

While one with do...end passed to wrong target method?

class OtherClass
  include Parser::Http.new do |agent|
    # FAILED: This block was passed to Module::include
  end
end

How to make this both syntaxes work the same?

like image 436
Molfar Avatar asked Mar 09 '26 04:03

Molfar


1 Answers

TL;DR do end has lower precedence than { }.

Actually, those syntaxes are not intended to work in the same way.

Here is a snippet from the official docs:

The block argument sends a closure from the calling scope to the method.

The block argument is always last when sending a message to a method. A block is sent to a method using do ... end or { ... }:

my_method do
  # ...
end

or:

my_method {
  # ...
}

do end has lower precedence than { } so:

method_1 method_2 {
  # ...
}

Sends the block to method_2 while:

method_1 method_2 do
  # ...
end

Sends the block to method_1. Note that in the first case if parentheses are used the block is sent to method_1.

Hope this helps.

like image 161
Marian13 Avatar answered Mar 11 '26 17:03

Marian13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!