Monday, 26 August 2019

How to find the missing elements in an array using ruby?

Input: a= [3, 4, 5, 6, 7, 15]

min_element  = a.min
max_element = a.max
new_missing_elements = []

for i in (min_element..max_element)
   new_missing_elements.push(i) unless a.include?(i)
end

print new_missing_elements

OUTPUT:

=>[8, 9, 10, 11, 12, 13, 14]

Friday, 2 August 2019

Class method calling in ruby?

Class methods:
We can call the class method by using class name.

class MyClass
   def self.my_method
     puts 'i am class method'
  end
end

 
 
MyClass.my_method
output=>
i am class method

Tuesday, 9 July 2019

How to find a given number is prime or not in ruby?

def check_prime n
    (2..n-1).each do |no|
         return false if n % no == 0
    end
    true
end

Tuesday, 2 July 2019

How to multiply the array elements in ruby?

a= [1,2,3,4,5,6,7,8]

Scenarios 1:
a.reduce(:*)

Scenarios 2:
b=1

a.each do |e|
  b=b*e
end


Factorial program using ruby

def factorial_no
  yield
end

n=gets.to_i
factorial_no do
  (1..n).reduce(:*)
end


Monday, 17 June 2019

How to Find the sum of total elements in an array using ruby?

a= [1,2,3,4,54,656,76,43,560]

Solution 1:

a.inject(&:+)

output: =>1399

Solution 2:

b = 0
a.each do |e|
  b+=e
end
b

output: =>1399

Friday, 17 May 2019

Find the uniq elements in an array without using ruby default method?

a = [1, 2, 3, 4, 5, 6, 4, 3, 2, 1, 4, 5, 4, 34, 76]

Solution:

b = Hash.new 0

a.each do |k|
  b[k] += 1
end

b.keys

Output:
=> [1, 2, 3, 4, 5, 6, 34, 76]

Interactor in Rails

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