0

Given a module Bam, and assuming that method Bam.[] is defined, the [] method can be called with a block in non-syntax sugar form like:

Bam.[]('boom') do |a|
  puts a
end

How can I call the [] method with a block in syntax sugar form Bam['boom']?

I tried the following:

Bam['boom'] do |a|
  puts a
end

Bam['boom'] {|a|
  puts a
}

They raise a syntax error.

I'm not looking for naming alternatives to []. Ruby provides nice syntactic sugar, so I prefer [] over other names.

1
  • Ruby's syntax is flexible, but it has limits. You've pushed it too far here. Commented May 10, 2017 at 8:24

2 Answers 2

3

[] is a shortcut, and it may not be designed to accept blocks.

Either use a traditional method (which in this case is only 1 char longer):

module Bam
  def self.get(a)
    yield a
  end
end

Bam.get('boom') do |a|
  puts a
end

or the explicit method syntax Bam.[]('boom').

I assume yours is only an example, as the original method definition doesn't make a lot of sense.

Sign up to request clarification or add additional context in comments.

Comments

0

The closest thing I can think of is Ruby's & operator to convert a proc to a block:

block = proc { |a| puts a }
Bam['boom', &block]

Or without a variable:

Bam['boom', &proc { |a| puts a }]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.