1

I used to have this method:

def send_action(action, &success_block)

end

Which I could call like this:

send_action('PAIR') do
  pp 'test
end

Now I want to add an optional parameter:

def send_action(action, uuid = nil, &success_block)

end

But that doesn't seem to work (which I though). So I tried writing it with named parameters:

def send_action(action:, uuid: nil, &success_block)

end

But how can I combine named parameters with a block?

1
  • 1
    def send_action(action, uuid = nil, &success_block) Works For Me™. What error are you seeing? And what version of Ruby are you using? Commented Sep 18, 2019 at 16:29

1 Answer 1

2

Both work with Ruby 2.4.4 and 2.6.4. Here's a demonstration with positional parameters.

def send_action(action, uuid = nil, &success_block)
  p "#{action} #{uuid}"
  success_block.call
end

send_action("foo") { p 99 }
"foo "
99

send_action("foo", "bar") { p 99 }
"foo bar"
99

And with named parameters.

def send_action(action:, uuid: nil, &success_block)
  p "#{action} #{uuid}"
  success_block.call
end

send_action(action: "foo") { p 99 }
"foo "
99

send_action(action: "foo", uuid: "bar") { p 99 }
"foo bar"
99
Sign up to request clarification or add additional context in comments.

1 Comment

You are correct, I had a missing comma. Both work fine, thanks for the example!

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.