Showing posts with label Ruby programs for practice. Show all posts
Showing posts with label Ruby programs for practice. Show all posts

Ruby Code Examples



Here I will provide Ruby Code Examples for all basic ruby programs of String, Array, Logical programs and Number based programs. In Ruby programming language.

Array Based Logical Programs


Ruby program to remove duplicate values in array

Program to find the second smallest number in an array in ruby

Find second largest number from an array in Ruby

Find smallest element in array without using min function in Ruby

Find largest element in array without using max function in Ruby

String Based Logical Programs

Ruby program to remove duplicate characters of a string

Ruby program to find occurrence of character in string

Find smallest and longest substring of a string in Ruby

Ruby program to reverse string without using direct method

Ruby program to convert full name into initials

Ruby program to remove common characters from two strings

Ruby program to remove vowels from string

Ruby program to search a string in a sentence

Number Based Logical Programs

Strong number program in Ruby


Prime number program in Ruby

Write a Ruby program to check the armstrong number

Ruby program for random number between two numbers

Ruby program to check Palindrome Number

Ruby program to reverse a number

Ruby program to sum of digits of a number

Ruby program to calculate generic root

Write a Ruby program to swap two arrays

- Ruby program to split number into digits

- Ruby program to print perfect numbers from 1 to 1000

- Ruby program to check perfect number


Ruby program to remove duplicate values in array



Write a ruby program to remove duplicate values in array

class DeleteDuplicateElement
  def deleteDuplicateElement
    print "Enter the size of array"
    size = gets.chomp.to_i
    input_array = []
    print "Enter the elements of array"
    while size > 0 do 
      input_array.push(gets.chomp)
      size = size - 1 
    end
    print "Entered array is: #{input_array}"
    input_array.uniq!
    print "\nUniq array is: #{input_array}"
  end
end

p = DeleteDuplicateElement.new 
p.deleteDuplicateElement

Output:


Enter the size of array 5
Enter the elements of array 22
 33
 22
 11
 55
Entered array is: ["22", "33", "22", "11", "55"]
Uniq array is: ["22", "33", "11", "55"]


Program to find the second smallest number in an array in ruby



Write a program to find the second smallest number in an array in ruby

class SecondSmallest
  def findSecondSmallest
    print "Enter the size of array"
    size = gets.chomp.to_i
    input_array = []
    print "Enter the elements of array"
    while size > 0 do 
      input_array.push(gets.chomp.to_i)
      size = size - 1 
    end
    second_smallest = input_array.sort[1]
    print "Entered array is: #{input_array}"
    print "\nSecond smallest element is: #{second_smallest}"
  end
end

p = SecondSmallest.new 
p.findSecondSmallest

Output:


Enter the size of array 5
Enter the elements of array 88
 44
 22
 11
 99
Entered array is: [88, 44, 22, 11, 99]
Second smallest element is: 22


Find second largest number from an array in Ruby



Find second largest number from an array in Ruby

class SecondLargestElement
  def findSecondLargestElement
    print "Enter the size of array"
    size = gets.chomp.to_i
    print "Enter the elements of array"
    count = 0
    array = []
    while count < size do 
      array.push(gets.chomp.to_i)
      count = count + 1
    end 
    print "Input array is: #{array}"
    second_largest = array.sort[-2]
    print "\nSecond largest element of array is: #{second_largest}"
  end
end

p = SecondLargestElement.new 
p.findSecondLargestElement

Output:


Enter the size of array 5
Enter the elements of array 77
 44
 66
 88
 99
Input array is: [77, 44, 66, 88, 99]
Second largest element of array is: 88


Find smallest element in array without using min function in Ruby



Write a program to find smallest element in array without using min function in Ruby

class SmallestElement
  def findSmallestElement
    print "Enter the size of array"
    size = gets.chomp.to_i
    print "Enter the elements of array"
    count = 0
    array = []
    while count < size do 
      array.push(gets.chomp.to_i)
      count = count + 1
    end 
    min = array.first
    print "Input array is: #{array}"
    array.each do |n|
      min = n if min > n
    end
    print "\nSmallest element of array is: #{min}"
  end
end

p = SmallestElement.new 
p.findSmallestElement

Output:


Enter the size of array 5
Enter the elements of array 22
 99
 11
 44
 66
Input array is: [22, 99, 11, 44, 66]
Smallest element of array is: 11


Find largest element in array without using max function in Ruby



Write a program to find largest element in array without using max function in Ruby

class LargestElement
  def findLargestElement
    print "Enter the size of array"
    size = gets.chomp.to_i
    print "Enter the elements of array"
    count = 0
    array = []
    while count < size do 
      array.push(gets.chomp.to_i)
      count = count + 1
    end 
    max = array.first
    print "Input array is: #{array}"
    array.each do |n|
      max = n if max < n
    end
    print "\nLargest element of array is: #{max}"
  end
end

p = LargestElement.new 
p.findLargestElement

Output:


Enter the size of array 5
Enter the elements of array 44
 66
 22
 99
 77
Input array is: [44, 66, 22, 99, 77]
Largest element of array is: 99


Ruby program to find occurrence of character in string



Ruby program to find occurrence of character in string

class CountCharOccurrence
  def countCharOccurrence
    print "Enter the string"
    input_string = gets.chomp.downcase
    print "Enter the search character"
    search = gets.chomp.downcase
    count = 0 
    input_string.split("").each do |s|
      count = count + 1 if s == search
    end
    print "character #{search} occurrerd #{count} times"
  end
end

p = CountCharOccurrence.new 
p.countCharOccurrence

Output:


Enter the string Umesh kumar kushwaha
Enter the search character u
character u occurrerd 3 times


Ruby program to remove duplicate characters of a string



Ruby program to remove duplicate characters of a string

class RemoveDuplicateCharacter
  def removeDuplicateCharacter
    print "Enter your string: "
    input_string = gets.chomp
    modified_string = ""
    input_string.split("").each do |s|
      modified_string = (modified_string + s) unless  modified_string.split("").include? s 
    end
    print "Modified string: #{modified_string}"
  end
end

p = RemoveDuplicateCharacter.new 
p.removeDuplicateCharacter

Output:


Enter your string:  ummmmmeeeessshh kkkkumarrrr kkkusshwwwaha
Modified string: umesh karw


Ruby program to remove common characters from two strings



Ruby program to remove common characters from two strings

class RemoveCommonCharacters
  def removeCommonCharacter
    print "Enter the first string: "
    first_string = gets.chomp.downcase
    new_first = first_string
    print "Enter the second string: "
    second_string = gets.chomp.downcase
    new_second = second_string
    char_array = first_string.split("")
    char_array.each do |v|
      unless v == " "
        if second_string.include?v
          new_first = new_first.gsub(v, "")
          new_second = new_second.gsub(v, "")
        end 
      end
    end
    puts "Original strings"
    puts "First string: #{first_string}"
    puts "Second string: #{second_string}"
    puts "After removing common characters"
    puts "First string: #{new_first}"
    puts "Second string: #{new_second}"
  end
end

p = RemoveCommonCharacters.new 
p.removeCommonCharacter


Output:


Enter the first string:  umesh kumar kushwaha
Enter the second string:  rajesh singh
Original strings
First string: umesh kumar kushwaha
Second string: rajesh singh
After removing common characters
First string: um kum kuw
Second string: j ing


Ruby program to remove vowels from string



Write a Ruby program to remove vowels from string

class RemoveVowelFromString
  def removeVowels
    print "Enter the string: "
    main_string = gets.chomp.downcase
    new_tring = main_string
    vowels = ['a','e','i','o','u']
    vowels.each do |v|
      new_tring = new_tring.gsub(v, "")
    end
    puts "Original string - #{main_string}"
    puts "New string - #{new_tring}"
  end
end

p = RemoveVowelFromString.new 
p.removeVowels

Output:


Enter the string:  umesh kumar kushwaha
Original string - umesh kumar kushwaha
New string - msh kmr kshwh


Ruby program to search a string in a sentence



Write a Ruby program to search a string in a sentence.

class CountStringInSentence
  def countOccurance
     print "Enter the main sentence: "
     main_string = gets.chomp
     print "Enter the search string: "
     search_string = gets.chomp
     count = 0
     main_string.split(" ").each do |s|
       count = count + 1 if s.casecmp(search_string).zero?
     end
     print "search string '#{search_string}' occured #{count} times"
  end
end

p = CountStringInSentence.new 
p.countOccurance

Output:


Enter the main sentence:  samajh samajh ke samajh ko samjho
Enter the search string:  samajh
search string 'samajh' occured 3 times


Ruby program for random number between two numbers



Write a Ruby program for random number between two numbers

class RandomNumber
  def calculateRandomNumber
     print "Enter the starting range: "
     start_num = gets.chomp.to_i
     print "Enter the ending range: "
     end_num = gets.chomp.to_i
     random_num = Random.new.rand(start_num..end_num)
     print "Random number is #{random_num}"
  end
end

p = RandomNumber.new 
p.calculateRandomNumber

Output:


Enter the starting range:  10
Enter the ending range:  100
Random number is 66


Strong number program in Ruby



Write a strong number program in Ruby

A number is called strong number if sum of the factorial of its digit is equal to number itself. For example: 145 since

1! + 4! + 5! = 1 + 24 + 120 = 145

class StrongNumber
  def checkStrong
     print "Enter the number: "
     input_num = gets.chomp.to_i
     num = input_num
     sum = 0 
     while num > 0 do
       rem = num % 10 
       num = num / 10 
       sum = sum + factorial(rem)
     end
     if input_num == sum
       print "#{input_num} is a strong number"
     else 
       print "#{input_num} is not a strong number"
     end 
  end
  
  private
  
  def factorial(a)
    fact = 1 
    (1..a).each do |i|
      fact = fact * i 
    end
    return fact
  end 
end

p = StrongNumber.new 
p.checkStrong

Output:

Enter the number:  145
145 is a strong number


Prime number program in Ruby



Write a prime number program in Ruby

Prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.

class PrimeNumber
  def checkPrime
     print "Enter the number: "
     num = gets.chomp.to_i
     check = 0 
     if (num == 0) || (num == 1)
       check = 1 
     else 
       (2..(num - 1)).each do |i|
         if (num % i == 0) && (i != num)
           check = 1 
           break
         end
       end
     end
    if check == 0  
      print "#{num} is a prime number"
    else
      print "#{num} is not a prime number"
    end 
  end
end

p = PrimeNumber.new 
p.checkPrime

Output:

Enter the number:  13
13 is a prime number


Ruby program to sum of digits of a number



Write a Ruby program to sum of digits of a number

class SumNumberDigits
  def getSumOfDigits
    sum = 0 
    rem = 0 
    print "Enter the number: "
    num = gets.chomp.to_i 
    while num !=0 do
      rem = num % 10 
      num = num / 10 
      sum += rem 
    end
    print "Sum of digits of number is :" + sum.to_s
  end
end

p = SumNumberDigits.new 
p.getSumOfDigits

Output:


Enter the number:  12345
Sum of digits of number is :15


Ruby program to calculate generic root



Write a Ruby program to calculate generic root.

Generic Root: It sum of digits of a number unit we don't get a single digit.
Example:

Generic root of 4563: 4+5+6+3 = 18 since 18 is two digit numbers so 1 + 8 = 9
So, generic root of 4563 = 9


class GenericRoot
  def getGenericRoot
    sum = 0 
    rem = 0 
    print "Enter the number: "
    num = gets.chomp.to_i 
    while num >= 10 do
      sum = 0 
      while num != 0 do
        rem = num % 10 
        num = num / 10 
        sum += rem 
      end 
      (sum >= 10) ? (num = sum) : break
    end
    print "Generic root of given number is :" + sum.to_s
  end
end

p = GenericRoot.new 
p.getGenericRoot

Output:

Enter the number:  123456
Generic root of given number is :3


Ruby program to swap two arrays



Write a Ruby program to swap two arrays

class SwappingArray

  def doSwap
    a = []
    b = []
    c = []
    puts "Enter the first array values "
    (0..4).each do |i|
      a[i] = gets.chomp
    end
    puts "Enter the Second array values "
    (0..4).each do |i|
      b[i] = gets.chomp
    end
    puts "Array before swapping"
    puts "Array first: "+ a.to_s
    puts "Array second: "+ b.to_s
    c = a 
    a = b 
    b = c 
    puts "Array after swapping"
    puts "Array first: "+ a.to_s
    puts "Array second: "+ b.to_s
  end
end

p = SwappingArray.new 

p.doSwap

Output:



Enter the first array values 
 1
 2
 3
 4
 5
Enter the Second array values 
 11
 22
 33
 44
 55
Array before swapping
Array first: ["1", "2", "3", "4", "5"]
Array second: ["11", "22", "33", "44", "55"]
Array after swapping
Array first: ["11", "22", "33", "44", "55"]
Array second: ["1", "2", "3", "4", "5"]