Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's this Ruby syntax?

Tags:

ruby

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.

like image 446
TieDad Avatar asked Oct 15 '13 08:10

TieDad


People also ask

What does %I mean in Ruby?

The usage of "%I" is just to create hash keys from an array of strings, separated by whitespaces.

What does '@' mean in Ruby?

Instance variables Examples: @foobar. The variable which name begins which the character ` @ ', is an instance variable of self . Instance variables are belong to the certain object. Non-initialized instance variables has value nil .

What are symbols in Ruby?

What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource. A resource can be: a method.

What Does a colon mean in Ruby?

Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object. :apple.object_id.


2 Answers

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

like image 146
Marek Lipka Avatar answered Nov 15 '22 21:11

Marek Lipka


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
like image 41
Afzal Masood Avatar answered Nov 15 '22 23:11

Afzal Masood