1. Ruby class methods understood even by C# developer

    Hey there. This week was pretty interesting and rich for new stuff. I’ve started investigating Ruby and it’s object model and found quite an interesting repo on metaprogramming and ruby object model itself. You can take a look on it. But that wasn’t something i wanted to talk about. I was glad to find, how to create a method that could be used without creating an instance of class itself (class methods).

    module Foo
      class Bar
    	def bar_instance_method
    	  puts 'bar_instance_method worked'
    	end
    	
    	def self.bar_class_method
    	  puts 'bar_class_method worked'
    	end
    
    	class << self
    	  def bar_class_method_other_way
    	    puts 'bar_class_method_other_way worked'
    	  end
    	end
      end
    end
    
    puts Foo::Bar.new.bar_instance_method
    puts Foo::Bar.bar_class_method
    puts Foo::Bar.bar_class_method_other_way
    
    Hence i can’t tell a whole bunch of difference between a first and second ways of doing that. Ok. Now, if we need to extend a functionality of an existing instance of class:
    bar = Foo::Bar.new
    
    class << bar 
      def new_bar_instance_method
        puts 'new_bar_class_method'
      end
    end 
    
    bar.new_bar_instance_method
    
    And extend functionality of all the instances of class:
    class Foo::Bar
      def new_bar_inherited_instance_method
        puts 'new_bar_inherited_instance_method'
      end
    end
    
    bar.new_bar_inherited_instance_method
    
    Meta of the Foo::Bar is changed, so meta of all the instances is changed as well. As far as i understood from Ruby guide, there’s an instance of metaclass for each class, so changes to the base class make changes to child classes.

     
blog comments powered by Disqus