Home > Blockchain >  Use of ```self.[]``` in method definition in ruby
Use of ```self.[]``` in method definition in ruby

Time:03-19

Actually, I am experienced in NodeJS but I am very new to Ruby, I cannot understand how this piece of ruby code is working, can someone explain what exactly the self.call method and self.[] methods are doing in this Ruby code ?.

1. class Mine::Container
2. 
3. def self.call
4.    @containers || {}
5. end
6.
7. def self.[] namespace
8.    @containers ||= Hash.new{|h, k| h[k] = new }
9.    @containers[namespace]
10.  end
11.end

What exactly self.call, self.[] method is doing ?. What would I get back if I call Mine::Container.(). ?.

CodePudding user response:

Mine::Container.() is a shortcut for Mine::Container.call that means it would call the call class method which looks like this:

def self.call
  @containers || {}
end

And it returns the value of @containers if @containers is it is set, otherwise (if @containers is not nil or false) an empty hash is returned ({}).

Furthermore the def self.[] namespace defines a class method to that expect one argument namespace which can be called like this:

Mine::Container[namespace]
  • Related