11

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.

2 Answers 2

12

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

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

1 Comment

According to the Ruby Style Guide you should "Prefer proc.call() over proc[] or proc.() for both lambdas and procs."
1

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

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.