Friday, 3 May 2019

Finding Dividable by 2 values in an ruby array

a = [1,2,3,4,444,6,5,6,7,8,44,55,333,555,66,88]
b = []
a.each do |h|
  b.push(h) if (h%2) == 0
end
p b

output:=> [2, 4, 444, 6, 6, 8, 44, 66, 88]

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

Interactor in Rails

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