Reputation: 1600
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
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
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