Ruby Self in Layman Terms

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



Leave a reply



Submit