What does self mean in Ruby?
self
refers to the object that is currently in context.
In your example, self
is the class
itself and def self.method
is defining a class method. For example:
class MyClass
def self.method
puts "Hello!"
end
end
> MyClass.method
#=> "Hello"
You can also use self
on instances of a class.
class MyClass
def method_a
puts "Hello!"
end
def method_b
self.method_a
end
end
> m = MyClass.new
> m.method_b
#=> "Hello!"
In this case, self
refers to the instance of MyClass
.
There is a good blog post on self in Ruby here, or, as it was pointed out in the comments, there is some more on this in the Ruby documentation.
Ruby Method Explanation
options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
Create a new hash called options
. This will either be assigned to the last element in the arguments array, or an empty one if that is not a hash. In ruby, like python, using -1 as an array index gets you the last element in an array.
options[:add] = true if options.empty?
Set the value in the hash that matches the key :add
to true if the hash you just created is empty.
return add(*arguments) if options[:add]
return subtract(*arguments) if options[:subtract]
return the result of add
or subtract
with the same parameters you passed to this function, based on the state of the options
hash you just created.
For example:
arguments = [{}, {:add => false, :subtract => true}]
would induce the subtract method if used as your parameter.
What is delegation in Ruby?
Delegation is, simply put, is when one object uses another object for a method's invocation.
If you have something like this:
class A
def foo
puts "foo"
end
end
class B
def initialize
@a = A.new
end
def bar
puts "bar"
end
def foo
@a.foo
end
end
An instance of the B class will utilize the A class's foo
method when its foo
method is called. The instance of B
delegates the foo
method to the A
class, in other words.
Related Topics
Scraping a Site That Requires Login Username and Password on Two Separate Pages
Ruby/Rails Array of Strings to Postgresql Insert
Bundle Uses Wrong Ruby Version
Unexpected Value of _Callee_ When Including a Module - Is This a Ruby Bug
Can You 'Require' Ruby File in Irb Session, Automatically, on Every Command
Ruby Instance_Eval on a Class with Attr_Accessor
Arbitrary Precision Arithmetic with Ruby
Exclude Draft Articles from Solr Index with Sunspot
Test (With Rspec) a Controller Outside of a Rails Environment
Rails 3 and PDFkit. How to Specify Page Size
How to Figure Out Which Step I'Ve Just Executed in Cucumber's Afterstep Hook
How to Optimize Graphviz Output Width
How to Make Rake Db:Migrate Generate Schema.Rb When Using :SQL Schema Format