How to understand ‘self’ keyword in Ruby

How to understand 'self' keyword in Ruby.md

How to understand ‘self’ keyword in Ruby

I came across self keyword while I was learning Ruby on Rails. I actually don’t understand at first glance so I google for more explanation. The first hit search from stackoverflow is not easy for me to understand. I found this post is really helpful. But just like everybody says: “You need Hands-on experience”. You might not fully understand it until you actually code it. So here I am, try to explain after I try coding it.

class Coffee
    attr_accessor :name
    def print()
        puts "Coffee name is #{@name}"
    end
    def self.drink()
        puts "Drinking coffee"
    end
    class << self
        def freeze()
            puts "Freezing coffee"
        end
        def boil()
            puts "Boiling coffee "
        end
    end #end of 'class << self' bracket
end

I want to run this Coffee class. So I try above code with online ruby compiler from here.

Code Result Explanation
cfe = Coffee.new => #<Coffee:0x0055ea423a3680> Create an object (result will be different from yours)
cfe.name = "cappuccino" => “cappuccino” We assign name of ‘cfe’ to ‘cappuccino’
cfe.print => Coffee name is cappuccino We call print function to print out the name of coffee
cfe.drink => undefined method ‘drink’ for #<Coffee:0x0055ea423a3680 @name=“cappuccino”> We cannot call ‘drink’ function just like ‘print’. Remember self keyword in front of ‘drink’ function in Coffee class
Coffee.drink => Drinking coffee This time, we can call ‘print’ function. This is like static function in C++ or Java. We can call the function without creating an instance
Coffee.freeze => Freezing coffee In this case, we can still call like static function again. Note that this function is surrounded with class << self keyword and end keyword.
Coffee.boil => Boiling coffee Since this ‘boil’ function is also surrounded with class << self and end keyword, we can call like static function. We dont need to write self keyword in every function. Convenient, right?

No comments:

Post a Comment