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]

How to remove the duplicate pair in an array using ruby?

Scenario 1
 
a = ['R1,R2','R3,R4','R5,R6', 'R2,R1', 'R4,R3']

Result:

a.uniq {|x| x.split(",").sort.join(',')}

Output => ["R1,R2", "R3,R4", "R5,R6"]


Scenario 2

a = ['R1,R2','R3,R4','R5,R6', 'R2,R1', 'R4,R3']

Result:  

require 'set'
a.uniq {|x| Set.new(x.split(','))} 

Output => ["R1,R2", "R3,R4", "R5,R6"] 

Friday, 3 May 2019

Display the * values in triangle shape in ruby

for i in 1..10
  for j in 1..i
    print ('*')
  end
  print ("\n")
end


output:
*
**
***
****
*****
******
*******
********
*********
**********

Finding the repeated words count from an array in ruby

a = %w(hi this is rajkumar this is uthayaa this is testing for repeat and repeat string)
b = Hash.new 0
a.each do |w|
  b[w] += 1
end
puts b

output: => {"hi"=>1, "this"=>3, "is"=>3, "rajkumar"=>1, "uthayaa"=>1, "testing"=>1, "for"=>1, "repeat"=>2, "and"=>1, "string"=>1}

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]]


Interactor in Rails

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