A doubt about the Dir::[] class method

Hi,

I am learning Ruby from the poignant guide and in chapter 4 I came
across the Dir::[] class method in a particular code snippet.

I tried a few variations with the way this method is invoked :

  1. Dir::[‘d’].each {|file_name| puts file_name}
  2. Dir::.each {|file_name| puts file_name}
  3. Dir..each {|file_name| puts file_name}
  4. Dir[‘d’].each {|file_name| puts file_name}

The first call does not work but the remaining three do. I have not been
able to figure out why any one these invocations works/does not work.

Thanks.

Am Wed, 31 Oct 2012 15:06:40 +0900
schrieb trishna mohanty [email protected]:

Hi,

I am learning Ruby from the poignant guide and in chapter 4 I came
across the Dir::[] class method in a particular code snippet.

I tried a few variations with the way this method is invoked :

  1. Dir::[‘d’].each {|file_name| puts file_name}

This is invalid syntax and will cause a SyntaxError. :: must be
followed by either a constant or a method name.

  1. Dir::.each {|file_name| puts file_name}

This is actually the same as Dir. (your 3)), just using another
syntax.

  1. Dir..each {|file_name| puts file_name}

This is a call to the [] method of the Dir object (which indidentally
is a class). It is the same as your 4), but without the syntactic
sugar. There exist some other places in Ruby where method calls are
issued implicitely, the most prominent being operators such as + or -:

3 + 3 ==> 3.+(3)
1 - 2 ==> 1.-(2)

ary = [1, 2, 3]
ary[1] ==> ary.

You usually don’t do this, but it’s good to know that all these are
just method calls.

  1. Dir[‘d’].each {|file_name| puts file_name}

This is the normal way to do it; internally Ruby resolves it to your 3)
as explained above, but looks way better than doing the method call
implicitely.

The first call does not work but the remaining three do. I have not
been able to figure out why any one these invocations works/does not
work.

Btw. you can have a fifth variant:

  1. Dir.send(:[], ‘d’).each{|file_name| puts file_name}

Maybe this makes the method nature of the call even clearer to you, as
you directly instruct Ruby to call the [] method on the Dir object.

Thanks.

Vale,
Marvin