Monday, 8 April 2019

Ruby On Rails Questions with Answers(List 1)

1. Getter and Setter in ruby?
    By using the attr_* form instead, we can get the existing value and set a new value.
    attr_accessor: for getter and setter both
    attr_reader: for getter only
    attr_writer: for setter on


2. What is Modules in Ruby?
   A Ruby module is an important part of the Ruby programming language. It’s a major object-oriented feature of the language and supports multiple inheritance indirectly.

    A module is a container for classes, methods, constants, or even other modules. Like a class, a module cannot be instantiated,
    but serves two main purposes:
    Namespace
    Mix-in

    Modules as Namespace
    A lot of languages like Java have the idea of the package structure, just to avoid collision between two classes. Let’s look into an example to understand how it works.
 
    module Patterns
      class Match
        attr_accessor :matched
      end
    end
    module Sports
      class Match
        attr_accessor :score
      end
    end
    match1 = Patterns::Match.new
    match1.matched = "true"
    match2 = Sports::Match.new
    match2.score = 210


    In the example above, as we have two classes named Match, we can differentiate between them and prevent collision by simply encapsulating them into different modules.

    Modules as Mix-in
    In the object-oriented paradigm, we have the concept of Interfaces. Mix-in provides a way to share code between multiple classes. Not only that, we can also include the built-in modules like Enumerable and make our task much easier. Let’s see an example.
 
  module PrintName
      attr_accessor :name
        def print_it
          puts "Name: #{@name}"
        end
    end


    class Person
    include PrintName
    end


    class Organization
    include PrintName
    end


    person = Person.new
    person.name = "Rajkumar"
    puts person.print_it # => Name: Rajkumar
    organization = Organization.new
    organization.name = "Rajkumar testing"
    puts organization.print_it # => Name: Rajkumar testing


    Mix-ins are extremely powerful, as we only write the code once and can then include them anywhere as required.

3. What Constructor and Destructor in ruby?
    A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor may also contain the group of instructions or a method which will execute at the time of object creation.
 
 # class name  
    class Demo 
       
        # constructor 
        def initialize   
            puts "Welcome to GeeksforGeeks!"  
        end  
     
    end   
     
    # Creating Obejct
    Demo.new
    output : Welcome to GeeksforGeeks!

    #Ruby program to initialize instance
    # class name
    class Geeks
         
        # constructor
        def initialize
             
            # instance variable intialzation
            @inst_1 = "GeeksforGeeks"
            @inst_2 = "Sudo Placement"
        end
         
        # display method
        def display
            puts "Value of First instance variable is: #{@inst_1}"
            puts "Value of Second instance variable is: #{@inst_2}"
        end
    end
     
    # creating object
    obj1 = Geeks.new()
     
    # calling display method
    obj1.display()
    Value of First instance variable is: GeeksforGeeks
    Value of Second instance variable is: Sudo Placement


    Destructor in ruby

    You can use ObjectSpace.define_finalizer when you create the image file, and it will get invoked when the garbage man comes to collect. Just be careful not to reference the object itself in your proc, otherwise it won't be collected by the garbage man. (Won't pick up something that's alive and kicking)
    class MyObject
      def generate_image
        image = ImageMagick.do_some_magick
        ObjectSpace.define_finalizer(self, proc { image.self_destruct! })
      end
    end

4. What is attr_accessor v/s attr_accesible  in ruby?

   attr_accessor is a Ruby method that makes a getter and a setter.
   attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or update_attributes(attrs)
  
5. What is private v/s protected in ruby?
    protected methods can be called by any instance of the defining class or its subclasses.

    private methods can be called only from within the calling object. You cannot access another instance's private methods directly.

    class Test1
      def main_method
        method_private
      end

      private
      def method_private
        puts "Inside methodPrivate for #{self.class}"
      end
    end

    class Test2 < Test1
      def main_method
        method_private
      end
    end

    Test1.new.main_method
    Test2.new.main_method

    Inside methodPrivate for Test1
    Inside methodPrivate for Test2

    class Test3 < Test1
      def main_method
        self.method_private #We were trying to call a private method with an explicit receiver and if called in the same class with self would fail.
      end
    end

    Test1.new.main_method
    This will throw NoMethodError


    Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".

    class Test1
      def main_method
        method_protected
      end

      protected
      def method_protected
        puts "InSide method_protected for #{self.class}"
      end
    end

    class Test2 < Test1
      def main_method
        method_protected # called by implicit receiver
      end
    end

    class Test3 < Test1
      def main_method
        self.method_protected # called by explicit receiver "an object of the same class"
      end
    end


    InSide method_protected for Test1
    InSide method_protected for Test2
    InSide method_protected for Test3


    class Test4 < Test1
      def main_method
        Test2.new.method_protected # "Test2.new is the same type of object as self"
      end
    end

    Test4.new.main_method

    class Test5
      def main_method
        Test2.new.method_protected
      end
    end

    Test5.new.main_method
    This would fail as object Test5 is not subclass of Test1
    Consider Public methods with maximum visibility

No comments:

Post a Comment

Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...