Friday, 3 May 2019

Sequences of even numbers from an array in ruby

Finding the sequences of even numbers from an array in ruby


a = [1,2,3,4,444,6,5,6,7,8,44,55,333,555,66,88]
b = []
a.each_slice(2) do |l|
  if l && l[0] && l[0].even? && l[1] && l[1].even?
    b.push(l)
  end
  b
end
p b

output:  => [[444, 6], [66, 88]]


Wednesday, 1 May 2019

Jar Puzzle Problem Resolved in Ruby By Rajkumar

Jar Puzzle Problem in Ruby



In puzzle.rb.

require './get_array.rb'

class Puzzle
def initialize(jar_capacity, initial_state, final_states)
#maximum capacities of jars set by the users
@max_jar, @medium_jar, @small_jar = jar_capacity
#initial state configs set by the users
@start_states = initial_state
#final states configs set by the users
@final_states = final_states
@results = Array.new
@visited_memory = Hash.new
end

def display_data
visit_states(@start_states)
puts '=====Your Results with sequences====='
if !@results.empty?
@results.reverse.collect {|x| p x}
else
puts 'No Path Found'
end
end

def visit_states(jar_states)
jar_a, jar_b, jar_c = jar_states

#compared with final states given by the users
if(jar_a == @final_states[0] && jar_b == @final_states[1])
@results.push(jar_states)
return true
end

#check the states in already visited
if @visited_memory.key?([jar_a, jar_b, jar_c])
return false
end

@visited_memory[[jar_a, jar_b, jar_c]] = 1

#empty the jar_a
if(jar_a > 0)
#empty jar_a into jar_b
if(jar_a + jar_b <= @medium_jar)
if( visit_states([0,jar_a + jar_b,jar_c]) )
@results.push(jar_states)
return true
end
else
if( visit_states([jar_a - (@medium_jar - jar_b), @medium_jar, jar_c]) )
@results.push(jar_states)
return true
end
end

#empty jar_a into jar_c
if(jar_a + jar_c <= @small_jar)
if( visit_states([0,jar_b,jar_a + jar_c]) )
@results.push(jar_states)
return true
end
else
if( visit_states([jar_a-(@small_jar - jar_c), jar_b, @small_jar]) )
@results.push(jar_states)
return true
end
end
end

#empty the jar_b
if(jar_b > 0)
#empty jar_b to jar_a
if(jar_a + jar_b <= @max_jar)
if( visit_states([jar_a + jar_b, 0, jar_c]) )
@results.push(jar_states)
return true
end
else
if( visit_states([@max_jar, jar_b - (@max_jar - jar_a), jar_c]) )
@results.push(jar_states)
return true
end
end

#empty jar_b into jar_c
if(jar_b + jar_c <= @small_jar)
if( visit_states([jar_a, 0, jar_b + jar_c]) )
@results.push(jar_states)
return true
end
else
if( visit_states([jar_a, jar_b - (@small_jar - jar_c), @small_jar]) )
@results.push(jar_states)
return true
end
end
end

#empty jar_c
if(jar_c > 0)
#empty jar_c into jar_a
if(jar_a + jar_c <= @max_jar)
if( visit_states([jar_a + jar_c, jar_b, 0]) )
@results.push(jar_states)
return true
end
else
if( visit_states([@max_jar, jar_b, jar_c - (@max_jar - jar_a)]) )
@results.push(jar_states)
return true
end
end

#empty jar_c into jar_b
if(jar_b + jar_c <= @medium_jar)
if( visit_states([jar_a, jar_b + jar_c, 0]) )
@results.push(jar_states)
return true
end
else
if( visit_states([jar_a, @medium_jar, jar_c-(@medium_jar - jar_b)]) )
@results.push(jar_states)
return true
end
end
end
return false
end

end

puts "=============Please enter jar capacities e.g. 8,5,3================"
total_capacities = GetArray.convert_array(gets.chomp)
puts "=============Please enter Initial configuration of jars e.g.=======8,0,0=="
initial_states = GetArray.convert_array(gets.chomp)
puts "=============Please enter the final configuration of jars==== e.g. 4,4,0========"
final_states = GetArray.convert_array(gets.chomp)
puzzle = Puzzle.new(total_capacities, initial_states, final_states)

puzzle.display_data


In get_array.rb

class GetArray
  def self.convert_array(inputs)
    if inputs != ''
      begin
        if inputs.split(',').map(&:to_i).size >=3
          inputs.split(',').map(&:to_i)
        else
          raise 'Your input should be minimum three values'
          exit(1)
        end
      rescue Exception => e
        puts e.message
      end
    end
  end
end


Monday, 29 April 2019

Find Maximum Element in an array

 Find the maximum elements in an array using ruby

def max_value(array)
  max = array[0]
  array.each do |i|
    if i > array[0]
      max = i
    end
  end
  max
end

array = [6,7,8,9,43,3,22,675,343,5454]
max_value(array) #calling method

Array Sorting Algorithm in Ruby

SORTING ALGORITHM
def sort_list(array)
  n = array.length - 1

  n.times.each do |l|
    min_index = l
    for j in (l+1)..n
      min_index = j if array[j] < array[min_index]
    end

    array[l], array[min_index] = array[min_index], array[l] if min_index != l
  end
array
end

sort_list([65,565656,43,3,2,1,0,9,6]) # to call the method

Wednesday, 10 April 2019

Ruby On Rails Questions & Answers(List 2)

1. Single table inheritance
In Single-Table Inheritance (STI), many subclasses inherit from one superclass with all the data in the same table in the database. The superclass has a “type” column to determine which subclass an object belongs to.
    class Vehicle < ApplicationRecord
    end
    class Bicycle < Vehicle
    end
    class Motorcycle < Vehicle
    end
    class Car < Vehicle
    end

In a polymorphic association, one model “belongs to” several other models using a single association. Each model, including the polymorphic model, has its own table in the database.
    class Post
     belongs_to :postable, polymorphic: true
    end
    class Person
     has_many :posts, as :postable
    end
    class Group
     has_many :posts, as :postable
    end


2. Design Patterns In Rails
Basic design patterns in Ruby on Rails. software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can > be transformed directly into source or machine code.
    1. Services
    2. Decorator
    3. Serializer

3. Singleton methods in ruby
A singleton method is a method that is defined only for a single object.
Instance methods are methods of a class (i.e. defined in the class's definition). Class methods are singleton methods on the Class instance of a class -- they are not defined in the class's definition. Instead, they are defined on the singleton class of the object.

    foo = Array.new
    def foo.size
      "Hello World!"
    end
    foo.size  # => "Hello World!"
    foo.class # => Array


    #Create another instance of Array Class and call size method on it
    bar = Array.new
    bar.size  # => 0
    foo.singleton_methods  # => [:size]
    bar.singleton_methods  # => []


4.class_eval v/s instance_eval
    Foo = Class.new
    Foo.class_eval do
      def class_bar
        "class_bar"
      end
    end
    Foo.instance_eval do
      def instance_bar
        "instance_bar"
      end
    end
    Foo.class_bar       #=> undefined method ‘class_bar’ for Foo:Class
    Foo.new.class_bar   #=> "class_bar"
    Foo.instance_bar       #=> "instance_bar"
    Foo.new.instance_bar   #=> undefined method ‘instance_bar’ for #<Foo:0x7dce8>


    class_eval
    mod.class_eval(string [, filename [, lineno]]) => obj
    Evaluates the string or block in the context of mod. This can be used to add methods to a class.

    instance_eval
    obj.instance_eval {| | block } => obj


    Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables.

5. Include vs Extend in Ruby
Now that we know the difference between an instance method and a class method, let’s cover the difference between include and extend in regards to modules. Include is for adding methods to an instance of a class and extend is for adding class methods. Let’s take a look at a small example.
    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>

Tuesday, 9 April 2019

What is overloading & overriding in ruby?

Overloading

 Method overloading in programing refers to invoking different behavior of a method of class depending on its arguments. Making it simpler, you can say that a class can have more then one method with the same name, but with different argument i,e different signature of the method.

You can implement different signature of method in any of the below way:

1 : Arguments with different data types, eg: method(int a, int b) method(string a, string b)

2:  Variable number of arguments, eg: method(a) vs method(a, b)

    class Person

      def print_details(name)
        "Hey My Name is #{name}"
      end

      def print_details(name,age)
        "Hey My Name is #{name} and #{age}"
      end
    end


    person1 = Person.new
    puts person1.print_details("Rajkumar")
    puts person1.print_details("Rajkumar",25)

    print_details’: wrong number of arguments (1 for 2) (ArgumentError)

So, you can see that, overloading not happening here. ruby expecting print_details to have two argument, but since in the first call, you passed only one argument, it throws error. So we can say that:Ruby do not support method overloading

In ruby there can be only one method with a given name. If there is multiple methods with the same name,the last one prevail i,e the last method will be invoked when called.

Overriding

In object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass overrides (replaces) the implementation in the superclass.

    class A 
      def a 
        puts 'In class A' 
      end 
    end 
     
    class B < A 
      def a 
        puts 'In class B' 
      end 
    end 
     
    b = B.new 
    b.a  #In class B

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

Interactor in Rails

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