Khoa Nguyen
Khoa Nguyen

Reputation: 1600

Syntax to pass block to '[]' ruby method

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.

Upvotes: 0

Views: 68

Answers (2)

Stefan
Stefan

Reputation: 114138

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 }]

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176372

[] 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.

Upvotes: 3

Related Questions