Showing posts with label Ruby Code Examples. Show all posts
Showing posts with label Ruby Code Examples. 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


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 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 convert full name into initials



Write a Ruby program to convert full name into initials

Example.

Enter your name
Umesh kumar kushwaha
Initials are U.K.K.


class FullNameToInitials
  def fullNameToInitials
    print "Enter the name: "
    name = gets.chomp
    initial_name = ""
    name.split.each do |n|
      initial_name = initial_name +  n[0].upcase + "."
    end 
    puts "Initial name is: #{initial_name}"
  end
end

p = FullNameToInitials.new 
p.fullNameToInitials

Output:

Enter the name:  Umesh kumar kushwaha
Initial name is: U.K.K.


Ruby program to reverse string without using direct method



Write a Ruby program to reverse string without using direct method

class ReverseString
  def reverseString
    print "Enter the string: "
    input_string = gets.chomp
    reverse_string = ""
    (0..(input_string.length - 1)).reverse_each do |i|
      reverse_string = reverse_string + input_string[i]
    end
    puts "Reverse string is: #{reverse_string}"
  end
end

p = ReverseString.new 
p.reverseString

Output:

Enter the string:  umesh kumar kushwaha
Reverse string is: ahawhsuk ramuk hsemu


Program to find smallest and longest substring of a string in Ruby



Write a program to find smallest and longest substring of a string in Ruby

class FindSmallestAndLongestSubstring
  def findSmallestAndLongestSubstring
    print "Enter the string: "
    input_string = gets.chomp
    all_substrings = input_string.split(" ")
    smallest_string = all_substrings[0]
    longest_string = all_substrings[0]
    all_substrings.each do |s|
      smallest_string = s if smallest_string.length > s.length
      longest_string = s if longest_string.length < s.length
    end 
    puts "Smallest substring: #{smallest_string}"
    puts "Longest substring: #{longest_string}"
  end
end

p = FindSmallestAndLongestSubstring.new 
p.findSmallestAndLongestSubstring

Output:


Enter the string:  umesh kushwaha best ror developer
Smallest substring: ror
Longest substring: developer


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 check Palindrome Number



Write a Ruby program to check Palindrome Number

Palindrome Number: If the number is equal to it's reversed number, then the given number is a palindrome number. For example: 121 is a palindrome number while 122 is not.

class PalindromeNumber
  def checkPalindrom
     print "Enter the number: "
     input_num = gets.chomp.to_i
     num = input_num
     new_num = 0 
     while num > 0 do
       rem = num % 10 
       num = num / 10 
       new_num = (new_num * 10) + rem 
     end
     if input_num == new_num
       print "#{input_num} is a palindrome number"
     else 
       print "#{input_num} is not a palindrome number"
     end 
  end
end

p = PalindromeNumber.new 
p.checkPalindrom

Output:

Enter the number:  1221
1221 is a palindrome number


Ruby program to check the armstrong number



Write a Ruby program to check the armstrong number

Example of armstrong number:
Input - 153
Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no.


class ArmstrongNumber
  def checkArmstrong
    print "Enter the number: "
    input_num = gets.chomp.to_i
    num = input_num
    check = 0 
    while (num > 0) do 
      rem = num % 10 
      num = num / 10 
      check = check + (rem * rem * rem)
    end
    if check == input_num
      print "#{input_num} is an armstrong number"
    else
      print "#{input_num} is not an armstrong number"
    end 
  end
end

p = ArmstrongNumber.new 
p.checkArmstrong

Output:

Enter the number:  371
371 is an armstrong number


Ruby program to reverse a number



Write a Ruby program to reverse a number


class ReverseNumber
  def checkReverse
     print "Enter the number: "
     input_num = gets.chomp.to_i
     num = input_num
     new_num = 0 
     while num > 0 do
       rem = num % 10 
       num = num / 10 
       new_num = (new_num * 10) + rem 
     end
      print "Reverse of #{input_num} is #{new_num}"
  end
end

p = ReverseNumber.new
p.checkReverse

----------------------------------------------------------------------------

class ReverseNumber
  def doReverse
    print "Enter the number: "
    num = gets.chomp
    rev = num.reverse.to_i
    print "Reverse of number is #{rev}"
  end
end

p = ReverseNumber.new 
p.doReverse

Output:


Enter the number:  852
Reverse of number is 258


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