Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does [ ] work on a class in Ruby

Tags:

class

ruby

I see that I can get a list of files in a directory using

Dir["*"]

How am I supposed to read that syntax exactly ? As I know that you can use [ ] to fetch a value from a array or a hash.

How does [ ] work on a call ?

like image 749
Prakash Raman Avatar asked Aug 25 '15 18:08

Prakash Raman


2 Answers

[] is simply a method, like #to_s, #object_id. etc.

You can define it on any object:

class CoolClass
  def [](v)
    puts "hello #{v}"
  end
end

CoolClass.new["John"] # => "hello John"

In your case it's defined as singleton method, in this way:

class Dir
  def self.[](v)
    ...
  end
end
like image 148
arthur.karganyan Avatar answered Sep 25 '22 13:09

arthur.karganyan


From the Ruby Docs, Dir["*"] is equivalent to Dir.glob(["*"]). (As pointed out, it's syntactic sugar)

Dir isn't a call, it's a class, and objects of class Dir are directory streams, which you access like an array.

In your specific case, Dir["*"] will return an array of filenames that are found from the pattern passed as Dir[patternString]. "*" as a pattern will match zero or more characters, in other words, it will match everything, and thus will return an array of all of the filenames in that directory.

For your second question, you can just define it as any other method like so:

class YourClass
  def self.[](v)
    #your code here
  end
end
like image 28
Parker Avatar answered Sep 22 '22 13:09

Parker