Reputation: 9889
I just read the following code:
class Dir
def self.create_uniq &b ### Here, & should mean b is a block
u = 0
loop do
begin
fn = b[u] ### But, what does b[u] mean? And b is not called.
FileUtils.mkdir fn
return fn
rescue Errno::EEXIST
u += 1
end
end
io
end
end
I put my confusion as comment in the code.
Upvotes: 11
Views: 405
Reputation: 4551
The & prefix operator allow a method to capture a passed block as a named parameter. e.g:
def wrap &b
3.times(&b)
print "\n"
end
now if you call above method like this:
wrap { print "Hi " }
then output would be:
Hi Hi Hi
Upvotes: 1
Reputation: 51151
Defining method with &b
on the end allows you to use block passed to the method as Proc
object.
Now, if you have Proc
instance, []
syntax is shorthand to call
:
p = Proc.new { |u| puts u }
p['some string']
# some string
# => nil
Documented here -> Proc#[]
Upvotes: 12