Wednesday, 5 November 2014

assign default layout in controller

Here is the method to check layout in the controller. 

You can debug the controller self object and check there is any layout name like this..

self.action_has_layout?

before_filter :check_and_assign_default_layout
def check_and_assign_default_layout
    unless self.action_has_layout?
      self.action_has_layout = "my_layout"
    end
end



Thank You,
Uma Mahesh.
 

Friday, 24 October 2014

Ruby on Rails Interview Questions

Ruby Interview Questions



Ruby Interview Questions



1. What is a class method and how you will define it?
     Class methods are methods that are called on a class without creating instance of that class.

     # Way 1                                     # Way 2                                     #Way3  
         class Foo                               class Foo                                   class Foo; end
             def self.bar                             class << self                         def Foo.bar
                 puts 'class method'                 def bar                               puts 'class method'
             end                                                puts 'class method'        end
         end                                                  end end end
 
     Calling class method => Foo.bar



2. What is an instance method and how you will instantiate it?

    Instance methods are methods that are called on an instance of a class.

    # Way 1                                     # Way 2                                           # Way 3                  
      class Foo                                class Foo                                         class Foo; end
         def baz                                  attr_accessor :baz                          foo = Foo.new
          puts 'instance method'        end                                                  def foo.bar
         end                                       foo = Foo.new                                 puts 'instance method'
       end                                         foo.baz = 'instance method'            end
 
        Instantiating instance methods:

              a). f = Foo.new
                   f.bar

              b).  g = Foo.new

                    g.send(:bar)


              c). Foo.new.bar

3. What is singleton class and singleton method ? (http://www.devalot.com/articles/2008/09/ruby-singleton)
 
     A singleton method is a method that is defined only for a single object.
   
       o = "message"      # A string is an object
         def o.printme        # Define a singleton method for this object
              puts self
          end
      o.printme          # Invoke the singleton

   A method added to a single object rather than to a class of objects is known as a singleton method.
   The implicit class object to which such singleton methods are added is sometimes called a singleton class or singel class instead.


4. What are the closures in ruby?

      In Ruby, procs and lambdas are closures . Closure refers to an object that is both an invocable function and a variable binding for that function.

        When you create a proc or a lambda, the resulting Proc  object holds not just the executable block but also bindings for all the variables used by the block.


5. What is the difference between Proc and Lambda?

http://railsknowledge.blogspot.in/2014/10/what-is-difference-between-proc-and.html


6. What is the difference between Ruby 1.8.7 and 1.9.2?

http://railsknowledge.blogspot.in/2014/10/what-is-difference-between-ruby-187-and.html

7. What is a module and what is the use of it?

      Like a class, a module  is a named group of methods, constants, and class variables.
Modules are defined much like classes are, but the module  keyword is used in place of
the class  keyword. Unlike a class, however, a module cannot be instantiated, and it  cannot be subclassed. Modules stand alone; there is no “module hierarchy” of inheritance. Modules are used as namespaces and as mixins.
        Namespaces:
            Modules are a good way to group related methods when object-oriented programming
is not necessary.

        Mixins:
            The second use of modules mixins. If a module defines instance methods instead of the class methods, those instance methods can be mixed in to other classes.


8. What is the difference between collect,select, reject and inject in ruby?

http://railsknowledge.blogspot.in/2014/10/what-is-difference-between.html


9. What is Enumerator in ruby?

     An enumerator  is an Enumerable  object whose purpose is to enumerate some other object. To use enumerators in Ruby 1.8, you must require 'enumerator' . In Ruby 1.9, enumerators are built-in and no require  is necessary.


10.Difference between ‘load’ and ‘require’ in Ruby?

           The difference between load and require is that load includes the specified Ruby file every time the method is executed and require includes the Ruby file only once.

       • In addition to loading source code, require  can also load binary extensions to Ruby. Binary  extensions are, of course, implementation-dependent, but in C-based implementations, they typically take the form of shared library files with extensions like .so  or .dll .

       • load  expects a complete filename including an extension. require  is usually passed a library name, with no extension, rather than a filename. In that case, it searches for a file that has the library name as its base name and an appropriate source or native library extension. If a directory contains both an .rb  source file and a binary extension file, require  will load the source file instead of the binary file.

       • load  can load the same file multiple times. require  tries to prevent multiple loads of the same file. (require  can be fooled, however, if you use two different, but equivalent, paths to the same library file. In Ruby 1.9, require  expands relative paths to absolute paths, which makes it somewhat harder to fool.) require  keeps track of the files that have been loaded by appending them to the global array
$"  (also known as $LOADED_FEATURES ). load  does not do this.

      • load  loads the specified file at the current $SAFE  level. require  loads the specified library with $SAFE  set to 0 , even if the code that called require  has a higher value for that variable. See §10.5 for more on $SAFE  and Ruby’s security system. (Note that if $SAFE  is set to a value higher than 0 , require  will refuse to load any file with a tainted filename or from a world-writable directory. In theory, therefore, it should be safe for require  to load files with a reduced $SAFE  level.)

11. What is string interpolation in Ruby?
        We can embedded an expression in double coded string using curly brackets preceding with #. This is called string interpolation.
                  Name =”vijay”    
                  Puts “My name is #{name}”

12. what is the difference between dup and clone methods in Ruby?
   
        The Ruby built-in methods Object#clone and #dup produce copies of their receiver. They differ in the amount of context they copy. The dup method copies just the object's content, whereas clone also preserves things such as singleton classes associated with the object.

                  s1 = "cat"
                  def s1.upcase
                    "CaT"
                   end

                 s1_dup   = s1.dup
                 s1_clone = s1.clone
                 s1                    #=> "cat"
                 s1_dup.upcase         #=> "CAT"  (singleton method not copied)
                 s1_clone.upcase       #=> "CaT"  (uses singleton method)


13. Difference between include and extend in Ruby?
     
       Include is for adding methods to an instance of a class and extend is for adding class methods

module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end

Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>

As you can see, include makes the foo method available to an instance of a class and extend makes the foo method available to the class itself.


14. Defining  attr_access  like methods in Ruby?
         class Demo
             def self.test_accessor (*args)
              args.each do |e|
                       define_method(e) do
                            puts instance_variable_get("@#{e}")
                       end
                      define_method("#{e}=") do |val|
                         instance_variable_set("@#{e}",val)
                     end
             end
          end
         test_accessor :hello,:vijay
       end


15. What is the output  of x=1/2 in ruby?
           0 # zero
Division of one integer by another results in a truncated integer. This is a feature, not a bug. If you need a floating point number, make sure that at least one operand is a floating point.



16. Write a method in Ruby to display given number of Fibonacci series?
                 def fibonacci(n)
                         a,b = 0,1
                    n.times do
                      printf("%d\n", a)
                       a,b = b,a+b
                    end
                 end


17. Difference between String and Symbol in ruby?

      Symbols are Strings, just with an important difference, Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten.

  String: Strings are mutable, the Ruby interpreter never knows what that String may hold in terms of data. As such, every String needs to have its own place in memory.
       
       Example:
        puts "hello world".object_id    # => 3102960
        puts "hello world".object_id   # => 3098410

 Symbol: Every Symbol shares the same object id, and as such the same space on the heap. To further increase performance, Ruby will not mark Symbols for destruction, allowing you to reuse them again and again. Symbols are not only stored in memory, they are also keep track of via an optimized Symbols dictionary.

       Example:
          puts :"hello world".object_id  # => 239518
          puts :"hello world".object_id  # => 239518


18. What is true, false and nil in ruby?

   true evaluates to an object that is a singleton instance of TrueClass. Likewise, false and nil are singleton instances of FalseClass and NilClass.

   Note that true, false, and nil refer to objects, not numbers. false and nil are not the same thing as 0, and true is not the same thing as 1. nil behaves like false, and any value other than nil or false behaves like true.

19. Garbage collection in Ruby?

   ObjectSpace.garbage_collect, which forces Ruby’s garbage collector to run. Garbage collection functionality is also available through the GC module. GC.start is a synonym for ObjectSpace.garbage_collect. Garbage collection can be temporarily disabled with GC.disable, and it can be enabled again with GC.enable.

20. Program to find given String is palindrome or not?

      def palindrome?(str)
  str.length <= 1 or (str[0,1] == str[-1,1] and palindrome?(str[1..-2]))
      end

      puts palindrome?("aja")

     Without Recursion call:

       def palindrome?(string)
           string == string.reverse
       end

21. Difference between Array and Hash in Ruby?
 
       Arrays: Arrays are used to store collections of data. Each object in an array has an unique key assigned to it.
  We can access any object in the array using this unique key.
  The positions in an array starts from " 0 ". The first element is located at " 0 ", the second at 1st position etc.
   
       A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type,
  not an integer index.
  Hashes enumerate their values in the order that the corresponding keys were inserted.

 So we use arrays when the order matters
 We use hashes when we want the convenience of refering to objects by their labels


22. Program to reverse the given line in Ruby?

  words = %w(Son I am able she said)
  str = ""
  words.reverse_each { |w| str += "#{w} "}     # str is now "said she able am I Son "
 
 
23. Program to find given number is prime or not?

     def prime?(n)
       prime = false
       factor = 1
       if n== 0 or n == 1
          prime = false
       end

       for i in 1..(n-1)
          if n%i == 0
             factor = i
          end
       end

       if factor > 1
           prime = false
       else
           prime = true
       end
      return prime
     end

24. Program to find given number is palindrome or not ?

       def palindrome?(n)
 
          num = n

          while n>0
              dig = n%10
              reverse = reverse*10 + dig
              n = n/10
          end

          if num == reverse
            return true
          else
           return false
          end
      end

25. Program to find given number is odd or even?

    def odd_even?(n)
   if n%2 == 0
      return true
   else
     return false
   end
end


26. Program to print reverse of the given string?

       def str_reverse str

         reverse = ‘ ‘
         chars = str.each_char.to_a
         chars.size.times { reverse << chars.pop}
        puts reverse
       end

27. How to instantiate a module self.method in a class?

   If you want to have both class methods and instance methods mixed into a class when including a module, you may follow the pattern:
 YourModule
  module ClassMethods
    def a_class_method
      puts "I'm a class method"
    end
  end

  def an_instance_method
    puts "I'm an instance method"
  end

  def self.included(base)
    base.extend ClassMethods
  end
end

class Whatever
  include YourModule
end

Whatever.a_class_method
# => I'm a class methodmodule

Whatever.new.an_instance_method
# => I'm an instance method


 28. Object-oriented programming in Ruby

 http://railsknowledge.blogspot.in/2014/10/object-oriented-programming-in-ruby.html
 

Object-oriented programming in Ruby

Object-oriented programming in Ruby

There are three widely used programming paradigms there. 

Procedural programming
Functional programming 
Object-oriented programming. 


Ruby is an object-oriented language. It has some functional and procedural features too.

Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.

There are some basic programming concepts in OOP:
Abstraction
Polymorphism
Encapsulation
Inheritance

The abstraction is simplifying complex reality by modeling classes appropriate to the problem. 

The polymorphism is the process of using an operator or function in different ways for different data input.

The encapsulation hides the implementation details of a class from other objects.

The inheritance is a way to form new classes using classes that have already been defined.

Objects

Objects are basic building blocks of a Ruby OOP program. An object is a combination of data and methods. In a OOP program, we create objects. These objects communicate together through methods. 

Each object can receive messages, send messages and process data.

There are two steps in creating an object.
First, we define a class. A class is a template for an object. It is a blueprint, which describes the state and behavior that the objects of the class all share. 
A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.

#!/usr/bin/ruby
class Being 
end

b = Being.new
puts b

In our first example, we create a simple object.
class Being
end

This is a simple class definition. The body of the template is empty. It does not have any data or methods.

b = Being.new

We create a new instance of the Being class. For this we have the new method. The b variable stores the newly created object.
puts b

We print the object to the console to get some basic description of the object. 
What does it mean, to print an object? When we print an object, we in fact call its to_s method. But we have not defined any method yet. It is because every object created inherits from the base Object. It has some elementary functionality, which is shared among all objects created. One of this is the to_s method.
$ ./simple.rb
#<Being:0x9f3c290>

We get the object class name.

The constructor

A constructor is a special kind of a method. It is automatically called, when the object is created. Constructors do not return values. The purpose of the constructor is to initiate the state of an object. The constructor in Ruby is called initialize. Constructors do not return any values.
Constructors cannot be inherited. The constructor of a parent object is called with a super method. They are called in the order of inheritance.

#!/usr/bin/ruby

class Being

    def initialize
        puts "Being is created"
    end

end

Being.new

We have a Being class.


The Being class has a constructor method called initialize. It prints a message to the console. The definition of a Ruby method is placed between the def and end keywords.
Being.new

An instance of the Being class is created. At the moment of the object creation, the constructor method is called.
$ ./constructor.rb
Being is created

This is the output of the program.

Object attributes is the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.

In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors.
#!/usr/bin/ruby

class Person

    def initialize name
        @name = name
    end

    def get_name
        @name
    end

end

p1 = Person.new "Jane"
p2 = Person.new "Beky"

puts p1.get_name
puts p2.get_name
In the above Ruby code, we have a Person class with one member field.
class Person
    def initialize name
        @name = name
    end

In the constructor of the Person class, we set a member field to a value name. The name parameter is passed to the constructor at creation. A constructor is a method called initialize that is being called at the creation of an instance object. The @name is an instance variable. Instance variables start with @ character in Ruby.
def get_name
    @name
end

The get_name method returns the member field. In Ruby member fields are accessible only via methods.
p1 = Person.new "Jane"
p2 = Person.new "Beky"

We create two objects of a Person class. A string parameter is passed to each object constructor. The names are stored inside instance variables that are unique to each object.
puts p1.get_name
puts p2.get_name

We print the member fields by calling the get_name on each of the objects.
$ ./person.rb
Jane
Beky

We see the output of the program. Each instance of the Person class has its own name member field.

We can create an object without calling the constructor. Ruby has a special allocate method for this. The allocate method allocates space for a new object of a class and does not call initialize on the new instance.
#!/usr/bin/ruby

class Being
   
   def initialize
       puts "Being created"
   end  
end

b1 = Being.new
b2 = Being.allocate
puts b2

In the example, we create two objects. The first object using the new method, the second object using the allocate method.
b1 = Being.new

Here we create an instance of the object with the new keyword. The constructor method initialize is called and the message is printed to the console.
b2 = Being.allocate
puts b2

In case of the allocate method, the constructor is not called. We call the to_s method with the puts keyword to show, that the object was created.
$ ./allocate.rb
Being created
#<Being:0x8ea0044>

Output of the program.

Constructor overloading

Constructor overloading is the ability to have multiple types of constructors in a class. This way we can create an object with different number or different types of parameters.

Ruby has no constructor overloading that we know from other programming languages.
This behaviour can be simulated to some extent with default parameter values in Ruby.
#!/usr/bin/ruby


class Person

    def initialize name="unknown", age=0
        @name = name
        @age = age       
    end
   
    def to_s
        "Name: #{@name}, Age: #{@age}"
    end

end

p1 = Person.new
p2 = Person.new "unknown", 17
p3 = Person.new "Becky", 19
p4 = Person.new "Robert"

p p1, p2, p3, p4

This example shows how we could simulate constructor overloading on a Person class that has two member fields. If we do not specify the name of the person, we have "unknown" string instead. For unspecified age we have 0.
def initialize name="unknown", age=0
    @name = name
    @age = age       
end

The constructor takes two parameters. They have a default value. The default value is used, if we do not specify our own values at the object creation. Note that the order of parameters must be kept. First comes the name, then the age.
p1 = Person.new
p2 = Person.new "unknown", 17
p3 = Person.new "Becky", 19
p4 = Person.new "Robert"

p p1, p2, p3, p4

We create four objects. The constructors take different number of parameters.
$ ./consover.rb
Name: unknown, Age: 0
Name: unknown, Age: 17
Name: Becky, Age: 19
Name: Robert, Age: 0

Output of the example.

Methods

Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are essential in encapsulation concept of the OOP paradigm. For example, we might have a connect method in our AccessDatabase class. We need not to be informed, how exactly the method connects to the database. We only have to know, that it is used to connect to a database. This is essential in dividing responsibilities in programming. Especially in large applications.
In Ruby, data is accessible only via methods.
#!/usr/bin/ruby

class Person

    def initialize name
        @name = name
    end

    def get_name
        @name
    end

end

per = Person.new "Jane"

puts per.get_name
puts per.send :get_name

The example shows two basic ways to call a method.
puts per.get_name

The common way is to use a dot operator on an object followed by a method name.
puts per.send :get_name

The alternative is to use a built-in send method. It takes a symbol of the method to be called as a parameter.

Methods typically perform some action on the data of the object.
#!/usr/bin/ruby

class Circle
  
    @@PI = 3.141592

    def initialize
        @radius = 0
    end

    def set_radius radius
        @radius = radius
    end

    def area
        @radius * @radius * @@PI
    end

end


c = Circle.new
c.set_radius 5
puts c.area

In the code example, we have a Circle class. We define two methods.
@@PI = 3.141592

We have defined a @@PI variable in our Circle class. It is a class variable. Class variables start with @@ sigils in Ruby. Class variables belong to a class, not to an object. Each object has access to its class variables. We use the @@PI to compute the area of the circle.
def initialize
    @radius = 0
end

We have one member field. It is the radius of the circle. If we want to modify this variable from the outside, we must use the publicly available set_radius method. The data is protected.
def set_radius radius
    @radius = radius
end

This is the set_radius method. It gives the @radius instance variable a new value.
def area
    @radius * @radius * @@PI
end

The area method returns the area of a circle. This is a typical task for a method. It works with data and produces some value for us.
c = Circle.new
c.set_radius 5
puts c.area

We create an instance of the Circle class. And set its radius by calling the set_radius method on the object of the circle. We use the dot operator to call the method.
$ ./circle.rb
78.5398

Running the example.

Access modifiers

Access modifiers set the visibility of methods and member fields. Ruby has three access modifiers: 
public, protected and private. 

In Ruby, all data members are private. Access modifiers can be used only on methods. 
Ruby methods are public, unless we say otherwise.

The public methods can be accessed from inside the definition of the class as well as from the outside of the class. 

The difference between the protected and the private methods is subtle. 
They both cannot be accessed outside the definition of the class. They can be accessed only within the class itself and by inherited or parent classes.

Note that unlike in other object-oriented programming languages, inheritance does not play role in Ruby access modifiers.

Only two things are important. First, if we call the method inside or outside the class definition. Second, if we use or do not use the self keyword which points to the current receiver.

Access modifiers protect data against accidental modifications. They make the programs more robust. The implementation of some methods is subject to change. These methods are good candidates for being private. The interface that is made public to the users should only change when really necessary. Over the years users are accustomed to using specific methods and breaking backward compatibility is generally frowned upon.
#!/usr/bin/ruby

class Some
       
     def method1
         puts "public method1 called"
     end

    public
   
     def method2
         puts "public method2 called" 
     end
    
     def method3
         puts "public method3 called"
         method1
         self.method1
     end         
end

s = Some.new
s.method1
s.method2
s.method3

The example explains the usage of public Ruby methods.
def method1
    puts "public method1 called"
end

The method1 is public, even if we did not specify the public access modifier. It is because methods are public by default, if not specified otherwise.
public

  def method2
      puts "public method2 called" 
  end

  ...

Methods following the public keyword are public.
def method3
    puts "public method3 called"
    method1
    self.method1
end   

From inside the public method3, we call other public method. With and without the self keyword.
s = Some.new
s.method1
s.method2
s.method3

Public methods are the only methods that can be called outside the definition of a class as shown here.
$ ./public_methods.rb
public method1 called
public method2 called
public method3 called
public method1 called
public method1 called

Running the example.

The next example looks at private methods.
#!/usr/bin/ruby


class Some
   
    def initialize
        method1
        # self.method1
    end

    private
   
     def method1
         puts "private method1 called" 
     end
          
end


s = Some.new
# s.method1

Private methods are tightest methods in Ruby. They can be called only inside a class definition and without the self keyword.
def initialize
    method1
    # self.method1
end

In the constructor of the method, we call the private method1. Calling the method with the self is commented. Private methods cannot be specified with a receiver.
private

  def method1
      puts "private method1 called" 
  end

Methods following the private keyword are private in Ruby.
s = Some.new
# s.method1

We create an instance of the Some class. Calling the method outside the class definition is prohibited. If we uncomment the line, the Ruby interpreter gives an error.
$ ./private_methods.rb
private method called

Output of the example code.

Finally, we will work with protected methods. The distinction between the protected and the private methods in Ruby is subtle. Protected methods are like private. There is only one small difference. They can be called with the self keyword specified.
#!/usr/bin/ruby

class Some
   
    def initialize
        method1
        self.method1
    end

    protected
   
     def method1
         puts "protected method1 called" 
     end
          
end


s = Some.new
# s.method1

The above example shows protected method in usage.
def initialize
    method1
    self.method1
end

Protected methods can be called with and without the self keyword.
protected

  def method1
      puts "protected method1 called" 
  end

Protected methods are preceded by the protected keyword.
s = Some.new
# s.method1

Protected methods cannot be called outside the class definition. Uncommenting the line would lead to an error.

Inheritance

The inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).
#!/usr/bin/ruby

class Being

    def initialize
        puts "Being class created"
    end
end

class Human < Being

   def initialize
       super
       puts "Human class created"
   end
end

Being.new
Human.new

In this program, we have two classes. A base Being class and a derived Human class. The derived class inherits from the base class.
class Human < Being

In Ruby, we use the < operator to create inheritance relations. The Human class inherits from the Being class.
def initialize
    super
    puts "Human class created"
end

The super method calls the constructor of the parent class.
Being.new
Human.new

We instantiate the Being and the Human class.
$ ./inheritance.rb
Being class created
Being class created
Human class created

First the Being class is created. The derived Human class also calls the costructor of its parent.

An Object may be involved in comlicated relationships. A single object can have multiple ancestors. Ruby has a method ancestors which gives a list of ancestors for a specific class.
Each Ruby object is automatically a descendant of Object, BasicObject classes and Kernel Module. They are built-in the core of the Ruby language.
#!/usr/bin/ruby


class Being
end

class Living < Being
end

class Mammal < Living
end

class Human < Mammal
end
   
   
p Human.ancestors

We have four classes in this example. A Human is a Mammal a Living and a Being.
p Human.ancestors

We print the ancestors of a Human class.
$ ./ancestors.rb
[Human, Mammal, Living, Being, Object, Kernel, BasicObject]

A Human class has three custom and three built-in ancestors.

A more complex example follows.
#!/usr/bin/ruby

class Being
   
    @@count = 0

    def initialize
        @@count += 1
        puts "Being class created"
    end
   
    def show_count
        "There are #{@@count} beings"
    end
   
end

class Human < Being

   def initialize
       super
       puts "Human is created"
   end
end

class Animal < Being

   def initialize
       super
       puts "Animal is created"
   end
end

class Dog < Animal

   def initialize
       super
       puts "Dog is created"
   end
end

Human.new
d = Dog.new
puts d.show_count

We have four classes. The inheritance hierarchy is more complicated. The Human and the Animal classes inherit from the Being class. And the Dog class inherits directly from the Animal class and further from the Being class. We also use a class variable to count the number of beings created.
@@count = 0

We define a class variable. A class variable begins with @@ sigils and it belongs to the class, not to the instance of the class. We use it to count the number of beins created.
def initialize
    @@count += 1
    puts "Being class created"
end

Each time the Being class is instantiated, we increase the @@count variable by one. This way we keep track of the number of instances created.
class Animal < Being
...

class Dog < Animal
...

The Animal inherits from the Being and the Dog inherits from the Animal. Further, the Dog inherits from the Being as well.
Human.new
d = Dog.new
puts d.show_count

We create instances from the Human and from the Dog classes. We call the show_count method on the Dog object. The Dog class has no such method; the grandparent's (Being) method is called then.
$ ./inheritance2.rb
Being class created
Human is created
Being class created
Animal is created
Dog is created
There are 2 beings

The Human object calls two constructors. The Dog object calls three constructors. There are two Beings instantiated.


Inheritance does not play role in the visibility of methods and data members. This is a notable difference from many common object-oriented programming languages.

In C# or Java, private data members and methods are not inherited. Only public and protected. In contrast to this, private data members and methods are inherited in Ruby as well. The visibility of data members and methods is not affected by inheritance in Ruby.
#!/usr/bin/ruby

class Base
   
    def initialize
        @name = "Base"
    end
   
    private
    
     def private_method
         puts "private method called"
     end
    
    protected
   
     def protected_method
         puts "protected_method called"
     end

    public
        
     def get_name
         return @name
     end
end


class Derived < Base

    def public_method
        private_method
        protected_method
    end
end

d = Derived.new
d.public_method
puts d.get_name

In the example we have two classes. The Derived class inherits from the Base class. It inherits all three methods and one data field.
def public_method
    private_method
    protected_method
end

In the public_method of the Derived class we call one private and one protected method. They were defined in the parent class.
d = Derived.new
d.public_method
puts d.get_name

We create an instance of the Derived class. We call the public_method. And call the get_name method, which returns the private @name variable. Remember that all instance variables are private in Ruby. The get_name method returns the variable regardless of the fact, that it is private and defined in the parent class.
$ ./inheritance3.rb
private method called
protected_method called
Base

The output of the example confirms that in Ruby language, public, protected, private methods and private member fields are inherited by child objects from their parents.

The super method

The super method calls a method of the same name in the parent's class. If the method has no arguments it automatically passes all its arguments. If we write super() no arguments are passed to parent's method.
#!/usr/bin/ruby

class Base
  
    def show x=0, y=0
        p "Base class, x: #{x}, y: #{y}"
    end
end

class Derived < Base

    def show x, y
        super
        super x
        super x, y
        super()
    end
end


d = Derived.new
d.show 3, 3

In the example, we have two classes in a hierarchy. They both have a show method. The show method in the Derived class calls the show method in the Base class using the super method.
def show x, y
    super
    super x
    super x, y
    super()
end

The super method without any arguments calls the parent's show method with the arguments that were passed to the show method of the Derived class. In our case x=3, y=3. The super() method passes no arguments to the parent's show method.
$ ./super.rb
"Base class, x: 3, y: 3"
"Base class, x: 3, y: 0"
"Base class, x: 3, y: 3"
"Base class, x: 0, y: 0"

Output of the example.






Thursday, 23 October 2014

What is the difference between collect,select, reject and inject in ruby?

What is the difference between collect,select, reject and inject in ruby?

     Some of the most commonly used Enumerable  iterators are the rhyming methods collect , select , reject , and inject .

       The collect  method (also known as map ) executes  its associated block for each element of the enumerable object, and collects the return values of the blocks into an array:
                 squares = [1,2,3].collect {|x| x*x} # => [1,4,9]

        The select  method invokes the associated block for each element in the enumerable
object, and returns an array of elements for which the block returns a value other than false  or nil . For example:
                 evens = (1..10).select {|x| x%2 == 0} # => [2,4,6,8,10]

        The reject  method is simply the opposite of select ; it returns an array of elements for
which the block returns nil  or false . For example:
                odds = (1..10).reject {|x| x%2 == 0} # => [1,3,5,7,9]

          The inject  method is a little more complicated than the others. It invokes the associated
block with two arguments. The first argument is an accumulated value of some sort from previous iterations. The second argument is the next element of the enumerable object. The return value of the block becomes the first block argument for the next iteration, or becomes the return value of the iterator after the last iteration.

          data = [2, 5, 3, 4]
          sum = data.inject {|sum, x| sum + x } # => 14 (2+5+3+4)
          floatprod = data.inject(1.0) {|p,x| p*x } # => 120.0 (1.0*2*5*3*4)

          max = data.inject {|m,x| m>x ? m : x } # => 5 (largest element)

What is the difference between Ruby 1.8.7 and 1.9.2?

What is the difference between Ruby 1.8.7 and 1.9.2?

   a).Pseudo-Keyword Hash Syntax
       Ruby 1.9 adds a cool feature that lets you write things like:
         foo(a: 1, b: 2)
         But on Ruby 1.8, we’re stuck using the old key => value syntax:
         foo(:a => 1, :b => 2)
   b).Multisplat Arguments
            Ruby 1.9.1 offers a downright insane amount of ways to process arguments to methods.
        def add(a,b,c,d,e)
           a + b + c + d + e
         end
    
       add(*[1,2], 3, *[4,5]) #=> 15
      The closest thing we can get to this on Ruby 1.8 would be something like  this:
       add(*[[1,2], 3, [4,5]].flatten) #=> 15

c).  Block-Local Variables
On Ruby 1.9, block variables will shadow outer local variables, resulting in the following behavior:
>> a = 1
=> 1

>> (1..10).each { |a| a }
=> 1..10
>> a
=> 1
This is not the case on Ruby 1.8, where the variable will be modified even if not explicitly set:
>> a = 1
=> 1
>> (1..10).each { |a| a }
=> 1..10

>> a
=> 10
d). Block Arguments
In Ruby 1.9, blocks can accept block arguments, which is most commonly seen in define_method:
define_method(:answer) { |&b| b.call(42) }
However, this won’t work on Ruby 1.8 without some very ugly workarounds

e).New Proc Syntax

Both the stabby Proc and the .() call are new in 1.9, and aren’t parseable by the Ruby 1.8 interpreter. This means that calls like this need to go:
>> ->(a) { a*3 }.(4)
=> 12
Instead, use the trusty lambda keyword and Proc#call or Proc#[]:
>> lambda { |a| a*3 }[4]
=> 12

f).Using Enumerator

In Ruby 1.9, you can get back an Enumerator for pretty much every method that iterates over a collection:
>> [1,2,3,4].map.with_index { |e,i| e + i }
=> [1, 3, 5, 7]
In Ruby 1.8, Enumerator is part of the standard library instead of core, and isn’t quite as feature-packed. However, we can still accomplish the same goals by being a bit more verbose:
>> require "enumerator"
=> true

>> [1,2,3,4].enum_for(:each_with_index).map { |e,i| e + i }
=> [1, 3, 5, 7]
 g). String Iterators
In Ruby 1.8, Strings are Enumerable, whereas in Ruby 1.9, they are not. Ruby 1.9 provides String#lines, String#each_line, String#each_char, and String#each_byte, all of which are not present in Ruby 1.8.

 h). Character Operations
In Ruby 1.9, strings are generally character-aware, which means that you can index into them and get back a single character, regardless of encoding:
>> "Foo"[0]
=> "F"
This is not the case in Ruby 1.8.6, as you can see:
>> "Foo"[0]
=> 70

 i).Encoding Conversions
Ruby 1.9 has built-in support for transcoding between various character encodings, whereas Ruby 1.8 is more limited. However, both versions support Iconv. If you know exactly what formats you want to translate between, you can simply replace your string.encode("ISO-8859-1") calls with something like this:
Iconv.conv("ISO-8859-1", "UTF-8", string)
j).Introduction of Fibers

Fibers are light-weight threads with manual, cooperative scheduling, rather than the preemptive scheduling of Ruby 1.8's threads.A fiber gets interrupted only when it yields its execution. So a fiber is a sort of user-managed thread. Threads use pre-emptive scheduling, whereas fibers use cooperative scheduling.
  

What is the difference between Proc and Lambda?

What is the difference between Proc and Lambda?

      Blocks are syntactic structures in Ruby; they are not objects, and cannot be manipulated
as objects. It is possible, however, to create an object that represents a block. Depending
on how the object is created, it is called a proc  or a lambda .

       Procs have block-like behavior and lambdas have method-like behavior. Both, however, are instances of class Proc .

       Creating & invoking procs:
             p = Proc.new {|x,y| x+y }
             p.call(1,2)
       
       Creating & invoking Lamdas:
            succ = lambda {|x| x+1}  =>Ruby1.8
               succ = ->(x){x>0} =>Ruby1.9
                succ.call(1)

        In a lambda-created proc, the return statement returns only from the proc itself
        In a Proc.new-created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!


      Differences:
        
Procs
Lambda
 A proc is the object form of a block, and it behaves like a block.

 Calling a proc is like yielding to a block.

 A proc is like a block, so if you call a proc that executes a return  statement, it attempts
to return from the method that encloses the block that was converted to the proc.
For Example:

def test
puts "entering method"
p = Proc.new { puts "entering proc"; return }
p.call  # Invoking the proc makes method return
puts "exiting method"  # This line is never executed
end
test

 break to do the same thing like return in a proc.


  proc handles the arguments it receives  flexibly:discarding extras, silently adding nil  for omitted arguments.

   p = Proc.new {|x,y| print x,y }
   p.call(1,2)  # prints 1,2
   p.call(1)  # prints 1, nil
 A lambda has slightly
modified behavior and behaves more like a method than a block.
 whereas calling a lambda is like invoking a method.

 A return  statement in a lambda returns from the lambda itself, not from the method that surrounds the creation site of the lambda:
For Example:
def test
puts "entering method"
p = lambda { puts "entering lambda"; return }
p.call
 # Invoking lambda does not make the method #return
puts "exiting method" 
# This line *is* executed now
end
test

break to do the same thing like return in a lambda.

 Lambdas are not flexible in this way; like methods, they must be invoked with precisely
the number of arguments they are declared with:

         l = lambda {|x,y| print x,y }
         l.call(1,2) # This works
         l.call(1) # Wrong number of arguments

   next statement works the same in a block, proc, or lambda.
   redo also works the same in procs and lambdas.
   retry is never allowed in procs or lambdas: using it always results in a LocalJumpError.
   raise behaves the same in blocks, procs, and lambdas. Exceptions always propagate up the call stack