1

I have seen a style of setting method parameters in a block (for example in Faraday) like this:

conn.post do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.body = '{ "name": "Unagi" }'
end
  1. What is this called?
  2. How does it work under the hood?

1 Answer 1

2

This is an example of a 'higher order function'. conn.post is a method that calls another method (which you define in the block)

This is a simple example:

def call_block; yield; end
puts call_block { true }
# => true

you can pass arguments to yield as well:

def yield_args(*args)
  yield args
end
yield_args(1, 2) { |item| item }
# => [1,2]
Sign up to request clarification or add additional context in comments.

2 Comments

Nice explanation. Could also be worth mentioning that the reason you would do this in a situation like the OP mentioned is that conn.post could do the initial work of creating the req object, provide that to the block to allow further customization of the object, and then possibly take further action with req after the customization has taken place.
I think this whole "you can turn a block into a proc like this" is irrelevant here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.