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 ?
[]
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With