Ruby Tutorials and Program List By Shiva Sir

150

What is Ruby:-

Ruby is a pure object-oriented programming language that is used to create desktop and web applications.

ruby language is easy to learn and contain various predefine library to implement program logic.

ruby is open source programming language, all software packages, tools, and frameworks are freely available, we can download ruby software and use in the program.


..........................................................................


Ruby Syntax:-


Ruby programming language can be written into three different patterns.


1)  Paragraph pattern:-


we will write a collection of statements similar to paragraphs.


puts("hello world")

puts("welcome")


2)  Procedural pattern:-


We will create a separate function to define the program, it provides a structured pattern to write the Ruby code.


def methodname()

     statements

     statements 

end


call 

methodname()


3)  OOPS Pattern:-


using this pattern we will create a class and object then define program code.


class Classname

   def methodname()

  

   end


end


obj = Classname.new

obj.methodname()


,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,


Ruby History:-


Ruby was created by Matz (Yukihiro Matsumoto) in 1990. it is influenced by C and shell script language. Ruby was released into the industry in 1993. 


,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,



Ruby Features:-


1)  Open source script


2)  Best in performance & Security


3)  Simple Syntax Structure


4)  Rich library to define in-built functionality


5)  Distributed


6)  Operating System Independent


7)  Multithreading support


8)  fully supported by oops


......................................................................



What is Rails?


It is the MVC-based web framework that is used to create a dynamic web application.

Rails framework is completely based on CLI(Command-line interface).



MVC means Model, View, and Controller, it is used to distribute the project on different project layers.

The model is used to create the data access layer, the view is used to create the user access layer, and the controller is used to create business code and work as an Intermediate between Model and View.


,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,


Ruby Operator?

The operator is used to perform the operation using operand, ruby not support increment and decrement operators.

1)  Arithmetic Operator:-

+   , -, *, **,/

2)  Conditional Operator or Relational Operator:-

<,>,<=,>=,!=

3)  Assignment Operator:-

  3.1)  Simple Assignment =

  3.2)  Complex Assignment 

   +=, -=,*=,/=,%=,**=

4)  Comparision Operator:-

   == to compare integer value or value type data type, eql it is used to compare object type data

5) Logical operator

&&   it will return true when all condition is true   

||        it will return true when only one condition is true

!       opposite of true and false

6) Ternary operator:-

It will solve the condition-based problem using a single-line statement.

(condition)?true:false


Conditional Statement in ruby:-

It is used to solve the condition-based problem using if, elsif, else statements, ruby also provide unless--else statement and case statement to solve the program.


1)  if condition then

       statement

     end


2)  if condition then

       statement

      else

        statement

      end


3)   Ladder if Else or Elsif

     if condition then

         statement

     elsif condition then

        statement

     else

      statement


4)  case option 

      when optionvalue then

         statement

     when optionvalue then

         statement

      ...

      else

         statement

 end



WAP to check vowels and consonants using case statements?


Soution:-

puts("Enter char")
s = gets().chomp
data=''
case s
when 'a' then
    data = 'vowel'
when 'e' then
    data = 'vowel'    
when 'i' then
    data = 'vowel'  
when 'o' then
    data = 'vowel'  
when 'u' then
    data = 'vowel'
else
    data = 'consonent'          
end  
puts(data)


Loop Statements in ruby:-

It is used to solve range-based problems using common repeatable statements, the loop will continuously be executed until the condition is false.

Loop is also called an iterative statement in a ruby programming language.


Loop uses three statements to execute the loop

                                  Forward                                        Backward                                                                                                                    

1) init                       i=min                                                          i=max

2)  condition            i<=max                                                        i>=min  

3) iteration              i=i+1                                                             i=i-1


Type of loop:-

1) While:-

      It provides an entry-level-based iterative statement, which means first checking the condition then executing the statement.

     Syntax

init

while conditioning then

  statement

  increment


Example of while loop:-

WAP to calculate factorial of any entered number?




ASSIGNMENTS?

 Q) WAP to print 1 to 5 and  5 to 1 using a single while loop?

Q) WAP to calculate square and cube of one digit positive number?

Q)WAP to print 1 to 5 and  5 to 1 again 1 to 5 and 5 to 1 using a single while loop?

Q)WAP to perform the addition of a one-digit positive number?  

Q) WAP to check the prime number?

Q)WAP to reverse any digit number?

Q) WAP to find max digit, second max digit in mobile number?

2)  do. while:-   First execute statement then check condition, it is also called exit control loop

loop do

statement

if condition

    break

end

increment|decrement



end

Example of do-while

3)  until:-  It is the opposite of the while loop, it will execute until the condition will be true.

init

until condition

statement

increment

end

WAP to print table using until--end?

num=21
i=1
until i>10
t = num*i
puts("#{t}")
i=i+1
end    


4)   for:-  It is used to provide simple syntax structure as compared to while, do-while and it'll because it will contain all components of a loop under a single line statement using range operator.

for I in start..end  

    statement

end


Example of for loop using ...

for i in 1...11
    puts("#{i}")
end  


Example of for loop using .. operator?

for i in 1..11
    puts("#{i}")
end    



Nested For Loop:-

We will write more than one for loop using the combination of the outer for loop and inner for loop, outer for loop will execute once after the inner for loop will execute till last, when the inner for loop condition will be false then the outer for loop will increase. and when the outer for loop condition is false then the loop will terminate.

for I in start..end

for j In start..end

print("data")

puts()


Example of Nested For Loop:-

for i in 5.downto(1)
    for j in 1..i
        print("*" )
    end
    puts()
end        



Another Loop Example:-

for i in 1..5
    for j in 1..i
        print("*" )
    end
    puts()
end        



Print Following Pattern:-

A B C D E
A B C D
A B C
A B
A
.............................................................

A
A B
A B C
A B C D
A B C D E

.....................................
I j
1 1
2 2
3 3
4 4
5 5

for i in range(1,6):
    for j in range(1,7-i):




Assignment of Nested For Loop In Python:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
............................................

A B C D E
a  b  c  d
A B C
a b
A


..........................................................

A  a B b C
A a B b
A a B
A a
A


.........................................................

1 2 3 4 5
5 4 3 2
1 2 3
5 4
1


......................................................................
1 0 0 1 0
1 0 0 1
1 0 0
1 0
1
...............................................................................


Create a Pattern to print this pattern:-

A B C D E
    B C D E
        C D E
           D E
               E


              *
        *      *       *
*     *       *       *     *
       *       *      *
                *


WAP to manage ATM operation with the following instruction

1)  When an application will be loaded then ask for the pin code, if the pin code is correct then the process to the next phase otherwise ask pin code three times if it will be wrong then the application will be closed automatically.


 2)   If the pin code is correct then ask for operation using the menu  Press C for Credit, D for Debit, B for check balance, E for the exit, R for a Repeat operation.

3)   If the user performs three operations then automatically exit from the application.

4)  Display all log means the internal process



What is Array?

The array is a collection of different types of elements using index=>value pair, the array is a special type of variable that can store multiple values in a single memory address.

Ruby array is dynamic in length means we can increase o decrease the size of the array dynamically.

Syntax of Array

x = Array,new(size,values)

or

x = []

or

x = [item1,item2,item3]


Example of Array:-

#x = [12,23,34,"C","C++"]
x=[]
x.push(12)  #add elements into stack
x.push(23)  
x.push(11)
x.pop()   #delete elements from stack
for i in 0...x.length
    puts(x[i])
end    

x.each do |y|
   puts(y)
end


Multidimensional Array:-

using this we can store elements based on rows and columns.


Syntax

arrayname = [[rows],[rows]]

Exmple of multidimensional array?

x = [[2,3,1],[7,11,9]]

for i in 0...2
    c=0
    for j in 0...3
       print(x[i][j]," ")
    end
    puts()

end    



A multidimensional array with different number of row elements:-

x = [[2,3],[7,11,9],[4,5,4]]

for i in 0...3
    c=0
    for j in 0...x[i].length
       print(x[i][j]," ")
    end
    puts()

end    




Array Assignments:-

1) WAP to sort the elements of the array in ascending order?

2)  WAP to find the max and second max element in an array?

3)  WAP to merge two arrays in one array?

4)  WAP to display duplicate elements in an array?

5) WAP to display unique elements in an array?

2 3 4 5 7 11 11 2 5    o/p   3 4 7

6) WAP to display prime elements in the array?

7) Addition of two matrices?

8) Multiplication of two matrices?


Hash in ruby:-

It is used to contain data in key=>value pair, it provides better search results as compared to the array.
it is also called collection objects in the ruby language.

Syntax of ruby
var = {key:value, key:value1}

Example of Hash:-
student = {rno:1001,sname:"Jay Kumar",branch:"IT",fees:45000}
student.each do |k,v|
    puts("#{k} is #{v}")
end  


Old Syntax of Hash

student = {:rno=>1001,:sname=>"Jay Kumar",:branch=>"IT",:fees=>45000}
student.each do |k,v|
    puts("#{k} is #{v}")
end  

 User define function in ruby:-

using this we can categorised the program code under individual named block that can be reused and provide better structure to complex code.

It is also called method approach in the Ruby language.

Syntax of method

def methodname()


end


methodname()


Example:-

def addition()
   a=10
   b=20
   c=a+b
   puts(c)
end

addition()


Type of Method in ruby:-

1) Default:-

We can provide input and output operations under the method body.

1.1)  With return type:-

           We can return the output from the function body that can be displayed under the calling function.

      def functionname()

          return data

      end

     var = functionname()

     print(var)      


1.2) Without return type: We can not return any data using without a return type, output will be defined under the function body.


def functionname()

      print(statement)

end

functionname()

2) Parametrised:-

We can define an argument under the function parameter that will be called from calling function to called function.

def methodname(param1,param2)

       Statement

end

methodname(value1,value2)

type of parametrised function:-

1.1)  With return type:-

           We can return the output from the function body that can be displayed under the calling function.

      def functionname(arg1,arg2)

          return data

      end

     var = functionname(arg1,arg2)

     print(var)      


1.2) Without return type: We can not return any data using without a return type, output will be defined under the function body.


def functionname(arg1,arg2)

      print(statement)

end

functionname()


def addition()   # default without return type
   a=10
   b=20
   c=a+b
   puts(c)
end
def substraction()   # default with return type
    a=10
    b=20
    c=a-b
    return c
 end
 
 def multiplication(a,b)
     puts(a*b)
 end
 
 def division(a,b)
    return a/b
end  
addition()
res = substraction()
puts(res)
multiplication(10,2)
res=division(10,2)
puts(res)


What is the default argument value?

in the ruby method, we can set the default value under the parameter, if we did not pass the parameter then the default value will be applied.

def functionname(a=10,b=20)

     print(a+b)

end

functionname()  #30

functionname(1,2)   #3

How to return multiple values under parameter?

def functionname(a=10,b=20)

    return a,b

end

r = functionname())


Pass variable-length parameters:-

we can pass nth number parameters in ruby method

def functionname(*a)

print(a)

end

functionname(10,20,30)

Assignment of  function 

Assignment of default function:-


1)  WAP to reverse a five-digit number using the no return type function.

2) WAP to perform addition of complex number using return type function

3)  WAP to create a salary calculator using no return type function

4)  WAP to calculate compound interest using no return type function.

Q) WAP to find max element using variable-length arguments?

1) WAP to create a mark sheet program using function takes the hash as an input variable

2)  Create an ATM Program using a parametrized function?

3) Create a Sorting program using parametrized function?

File Handling in ruby:-

A file is a collection of records, if we store information permanently under computer hardisc then we can file handling concept.

Syntax:-

var = File.new(filename,"mode")
file mode can be write, read, append

for write

var = File.new(filename,"w")
if var
   var.syswrite("statement")
end

for read

var = File.new(filename,"r")
if var
   s=var.sysread()
   print(s)
end


we can use other modes also (w+, r+)

Assignments:-

f = File.new("d://scs.txt","w")
if f
  f.syswrite("Welcome in file handling")
end


Read operation
f = File.new("d://scs.txt","r")
if f
  d=f.sysread(50)
  puts(d)
end

Another Example:-

aFile = File.new("d://scs.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
   aFile.each_byte {|ch| putc ch; putc ?. }
else
   puts "Unable to open file!"
endbyte {|ch| putc ch; putc ?. }
end


aFile = IO.readlines("d://scs.txt")
puts(aFile[0])
puts(aFile[1])
puts(aFile[2])


Write data to take input from user's?

f = File.new("d://scs.txt","w")
if f
  puts("Enter name")
  name=gets
  puts("Enter mobile no")
  mobile=gets  
  f.syswrite("name is #{name} and mobile is #{mobile}")
end



Rename and Delete the file:-

#File.rename("d://scs.txt","d://scsnew.txt")
File.delete("d://scsnew.txt")
'''





String Example in ruby:-

String is a collection of char using proper sequence, string indexing is similar to an array, String can be declared using '', "" both in ruby.

ruby provides String interpolation to write variables under String Literals.


Syntax of String 

String as a reference

s = "hello"

String as a Object

s = String.new("hello")


Note:-  String object is immutable because we can not change the value from the actual address.


How to iterate String object data?

s.each_char do |i|
    print(i)
end    

WAP to print only vowel in String?


s = "Hello"
#s1=s.downcase
#print(s1)
for i in 0...s.length
    if s[i] =='a' || s[i]=='e' || s[i] =='i' || s[i]=='o' || s[i]=='u'
       print(s[i])
    end
end    

 



Operation on String


1)  String extraction:-

We can split the String elements using String index.

s = "hello"

print(s[1,3])  #ell

2) String Interpolation:-

We can print variables or manage expressions using #{} which is called String interpolation.

a=10

b=20

s = "a= #{a} and b=#{b} and result = #{a+b}"

print(s)


Assignments of String:-

String-based Program

1) Count total vowel and consonant in String?

2)  WAP to reverse String?

3)  Convert upper case to lower case?

4)   Count total numeric char in String?

5) WAP to convert string elements in the opposite case?

6) WAP to validate email?

7) WAP to validate internet URL it can be HTTP, HTTP, and without HTTP?

8) WAP to check password strength, if it contains consecutive char, without any 3 special char, their name or last name then the password will be weak, if the password contains 3 special char, nonconductive char then the password will be strong?

5) WAP to display the largest palindromic in a string?

6) WAP to find total prepositions in a paragraph

Create Expenses System using File Handling Program:-
Program to create a resume using file handling?

Program to calculate SI using P, R, and T?

Program to calculate Simple Interest using Write and Read Mode?


Recursion:-
If a function calls itself from the inner body of the function to the outer body of a function, when we use return ten function calling will finish that process is called recursion.
recursion is the alternative statement of iterative statements.

def functionname()
       functionname()
end
   

# Ruby program for calculating the Nth Fibonacci number.
$a=0
def Add(number)
   
    # Base case : when N is less than 2.
    if number==0
        return $a
    else
   
        # Recursive call : sum of last two Fibonacci's.
        #$a = $a + Add(number-1)
        $a = $a +number
        return  Add(number-1)
    end
    end
   
print(Add(10))
   


Factorial Program in Ruby:-
# Ruby program for calculating the Nth Fibonacci number.
$a=1
def Fact(number)
   
    # Base case : when N is less than 2.
    if number==1
        return $a
    else
   
        # Recursive call : sum of last two Fibonacci's.
        #$a = $a + Add(number-1)
        $a = $a *number
        return  Fact(number-1)
    end
    end
   
print(Fact(5))
   


Fibonacci series,
Table Program,
Sum of even and odd number using recursion?
Assignment:-

1)  WAP to perform the addition of two numbers and write the output of addition under file?


2)  WAP to create complete biodata for a marriage proposal?


3)  WAP to create horoscope software?


OOPS Program:-

OOPS means Object-oriented programing structure, it is used to create a real-world-based application.

It provides Security, accessibility, extendibility, reusability, and usability features.


Rules of OOP:-

1) Class and Object:-

It is mandatory rules of oops

Class:- It is the blueprint of an object, it contains characteristics and behavior of object under single unit, class contains object data using data member and member function.


Example of class:-

class SI
   def accept(p,r,t)  
       @p=p
       @r=r
       @t=t
   end
   def logic()
      @si = (@p*@r*@t)/100
   end
   def display()
      puts("Result is #{@si}")
   end
end    
obj = SI.new
obj.accept(10000,2,2)
obj.logic()
obj.display()

What is an object?

It is a real-world entity, which contains identity state and behavior.  we can create user define objects which contain memory address as an identity, memory space as a state, and contain and access functionality as a member function.

address = Classname. new

new is used to create memory space.


Component of class:-

1) Data member and member function:-

It is used to define the attribute of the object, the data member will be declared as a variable and the member function will be declared as a method.

type of member function:-

1)  class type member function:-

this member function contains a single memory space to store data, it is also called a static member function and it will be defined by self keyword.

Syntax of Class type:-

class Classname:

def self. display

  statements

end

end


Classname.display


Example of Class type:-

class SI
   def self.accept(p,r,t)  
       @p=p
       @r=r
       @t=t
   end
   def self.logic()
      @si = (@p*@r*@t)/100
   end
   def self.display()
      puts("Result is #{@si}")
   end
end    

SI.accept(10000,2,2)
SI.logic()
SI.display()


2) instance type member function

This member function contains separate memory space to fo each object it contains dynamic memory space, In most cases, we prefer a dynamic member function.

class Classname:

def functionname()

  statements

end

end


obj = Classname.new()

obj.functionname()


Exampe of Instance type:-

class SI
   def accept(p,r,t)
       @p=p
       @r=r
       @t=t
   end
   def logic()
      @si = (@p*@r*@t)/100
   end
   def display()
      puts("Result is #{@si}")
   end
end    
obj = SI.new
obj.accept(10000,2,2)
obj.logic()
obj.display()


Type of data member:-

According to scope:-

global variable:- this type of variable will be declared globally means we can declare it above class also.

$var=10

class Classname

     def   methodname()

                 puts($var)

    end

end



Example:-

$a=10

class VarExample
   def displayVar()
        puts($a)
   end

   

end    

obj = VarExample.new
obj.displayVar()

local variable:-

if we declare a variable under the method block then its scope will be limited means it can not access outside of the method body.



class VarExample
   def displayVar()
        a=10
        puts(a)
   end

   

end    

obj = VarExample.new
obj.displayVar()


According to memory:-

1) Class type variable or Static Variable  @@:-

if we want to create single memory to variable incomplete program then we can declare it a class type variable.

It stores data under class memory, we can not re-allocate memory to class type variable.

class VarExample
    @@count=0
   def displayVar()
       
        @@count = @@count +1
       
        puts("class type variable=#{@@count}")
   end

end    

obj = VarExample.new
obj.displayVar()
obj1 = VarExample.new
obj1.displayVar()


note:-  if we want to create a shared variable then we can create a class type variable.

2) Instance type variable or dynamic variable @:-

This type of variable memory allocation will be managed by the object, it can store data into individual memory according to each object.

class VarExample
   
   def displayVar()
        @c=0
       
        @c=@c+1
        puts("instance type variable #{@c}")
   end

end    

obj = VarExample.new
obj.displayVar()
obj1 = VarExample.new
obj1.displayVar()


Initializers or init method or constructor:-

It is used to initialize the dynamic data member of the class, the initializers block will be called when we create the object.

class InitExample

    def initialize()
       @a=100
       @b=200
       puts("#{@a+@b}")
    end    

end  

obj = InitExample.new


type of initializer block:-

1) default initializer:-

  this block will be created implicitly if we want to manually create then it is not created implicitly.   it is used to initialize the instance data member value.

class InitExample

    def initialize()
       @a=100
       @b=200
       puts("#{@a+@b}")
    end    

end  

obj = InitExample.new


2) param initializer:-  we can pass the parameter value under the object to call parametrized initializer. in ruby, we can define only one initializer underclass


class InitExample
   
    def initialize(a,b)
       @a=a
       @b=b
       puts("#{@a+@b}")
    end    

end  

obj1 = InitExample.new(10,2)

Data abstraction and Data encapsulation:-

Data abstraction means hiding the non-essential details and showing essential details in the program. Data encapsulation means binding the data member or variable under a member function or property is called data encapsulation.


How to implement data abstraction?

Ruby provides an access specifier to implement data abstraction.

1) public: it can be accessed  outside of the class  then we can create public

2) protected:- it can be accessed  outside of the related class means base class to child class 

3)  private:-  it can not be accessed  outside of the class then we can create private


Example:-

class InitExample
   
   def fun1()
       puts("public")
       fun2()
       fun3()
   end
   protected
   def fun2()
    puts("protected")
   end
   private
   def fun3()
    puts("private")
   end
end  

obj1 = InitExample.new()
obj1.fun1()
#obj1.fun2()
#obj1.fun3()


Data abstraction and Encapsulation:-

class Bank

    def initialize()
      @bal=5000
     end  
    private  
    def credit(amt)
      @bal+=amt
    end  
    def debit(amt)
        @bal-=amt
    end  
    def checkbalance()
        puts("balance is #{@bal}")
    end    
    public
    def login(pin)
         if pin==1212
              credit(12000)
              checkbalance()
         end  
    end  
end
obj = Bank.new
obj.login(1212)


 

Data Encapsulation using getter and setter

Ruby provide an accessor method to provide a mode for data member of the class to read and write data.

1) attr_reader:- only for the read.

2) attr_writer:- only for write.

3) attr_accessor:- read and write both.

Example of attr_reader:-

class AccessorExample
   def initialize(scs)
    @scs=scs
   
   end
   attr_reader  :scs

end  

obj = AccessorExample.new("welcome in shiva concept")
puts(obj.scs)
#obj.scs = "ABC"


Example of attr_writer

class AccessorExample
   def initialize(scs)
    @scs=scs
   
   end
   attr_writer  :scs

end  

obj = AccessorExample.new("welcome in shiva concept")

#puts(obj.scs)
obj.scs = "ABC"


Example of accessor method:-

class AccessorExample
   def initialize(scs)
    @scs=scs
   
   end
   attr_accessor  :scs

end  

obj = AccessorExample.new("welcome in shiva concept")
puts(obj.scs)
obj.scs = "ABC"
puts(obj.scs)



Polymorphism:-

..........

Poly means many and morphism means forms using this we can create the same name method and operator that can be used in multiple functionalities.

Ruby supports operation loading and functions overriding concepts under polymorphism.

What is operator overloading?

we can define a single operator under multiple forms uisng operator overloading. we can overload + operator for addition as well as other operation.

Example of operator overloading:-


class Overload
   def initialize(a)
     @a=a
   end
   def +(obj)
     return obj-@a
   end
   def -(obj)
    return @a*obj
  end

end
o = Overload.new(50)

puts(o - 2)  


Inheritance:- it means reusability, using this we can acquire the functionality of parent class to the child class.

Type of Inheritance:-

1) Single Inheritance:-

We can access the features of the base class to the derived class.

class A


end


class B < A


end


Example of Single Inheritance:-

class Admin
    def accept(aid,aname)
       @aid=aid
       @aname=aname
    end
    def display()
        puts("id is #{@aid} and name is #{@aname}")
    end    

end    

class Manager < Admin
    def accept1(sal)
        @sal=sal
       
     end
     def display1()
         puts("Salary is #{@sal}")
     end    
end  

print("Manager Features")
mgr = Manager.new()
mgr.accept(1001,"Satendra")
mgr.accept1(12000)
mgr.display()
mgr.display1()

2) Multilevel Inheritance:-

We can access the features of the base class to the derived class and derived class to sub derived class.


class A


end


class B < A


end

class C < B


end

Example of Multilevel Inheritance:-

class Admin
    def accept(aid,aname)
       @aid=aid
       @aname=aname
    end
    def display()
        puts("id is #{@aid} and name is #{@aname}")
    end    

end    

class Manager < Admin
    def accept1(sal)
        @sal=sal
       
     end
     def display1()
         puts("Salary is #{@sal}")
     end    
end  

class Emp < Manager
    def accept2(bonus)
        @bonus=bonus
       
     end
     def display2()
         puts("Bonus is #{@bonus}")
     end    
end  

print("Emp Features")
mgr = Emp.new()
mgr.accept(1002,"Raj")
mgr.accept1(42000)
mgr.accept2(2000)
mgr.display()
mgr.display1()
mgr.display2()


Hierarchical Inheritance:-

It will provide an inheritance structure from one base class to multiple derived classes using a tree structure. one parent class contains multiple children where a parent will be the root node and the child will be sub-node.


class Admin
    def accept(aid,aname)
       @aid=aid
       @aname=aname
    end
    def display()
        puts("id is #{@aid} and name is #{@aname}")
    end    

end    

class Manager < Admin
    def accept1(sal)
        @sal=sal
       
     end
     def display1()
         puts("Salary is #{@sal}")
     end    
end  

class Emp < Admin
    def accept2(bonus)
        @bonus=bonus
       
     end
     def display2()
         puts("Bonus is #{@bonus}")
     end    
end  

print("Emp Features")
mgr = Emp.new()
mgr.accept(1002,"Raj")
#mgr.accept1(42000)
mgr.accept2(2000)
mgr.display()
#mgr.display1()
mgr.display2()


Multiple Inheritance:-

In this inheritance, two base classes features will be combined into a single child class, it is used to inherit the features of multiple classes into a single class but ruby does not support multiple inheritances because ruby has no principle to solve ambiguity problem.


Super() in ruby:-

using this we can call the parent class method to the child class:-

class Admin
    def accept(aid,aname)
       @aid=aid
       @aname=aname
    end
    def display()
        puts("id is #{@aid} and name is #{@aname}")
    end    

end    

class Manager < Admin
    def accept(sal)
        super(1001,"satendra")
        @sal=sal
       
     end
     def display()
        super()
         puts("Salary is #{@sal}")
     end    
end  


print("Manager Features")
mgr = Manager.new()
mgr.accept(12000)
mgr.display()


Exception Handling Program in ruby?

It is used to handle unexpected runtime errors in programs.  the exception is used to protect the program from interruption.

ruby provide "rescue" and  "ensure" and else block to execute statements

Syntax 1st

begin

code section

rescue

error message

end

Example

begin
puts("Enter First Number")
a=gets().to_i
puts("Enter Second Number")
b=gets().to_i
c=a/b
puts(c)
rescue
    print("Invalid data")
end    


2) Syntax 2nd:-

begin

code section

rescue

error message

ensure

default statements

end


begin
puts("Enter First Number")
a=gets().to_i
puts("Enter Second Number")
b=gets().to_i
c=a/b
puts(c)
rescue
    print("Invalid data")

ensure
    print("Hello Ruby")    
end    


Syntax 3rd:-

begin

code section

rescue

error message

else

if no any exception

ensure

default statements

end


Example

begin
puts("Enter First Number")
a=gets().to_i
puts("Enter Second Number")
b=gets().to_i
c=a/b
puts(c)
rescue
    print("Invalid data")
else
    print("NO ANY EXCEPTION")
ensure
    print("Hello Ruby")    
end    


retry statements:-

it is used to execute throw the cursor into the beginning block. it should be implemented under the rescue block.

begin
puts("Enter First Number")
a=gets().to_i
puts("Enter Second Number")
b=gets().to_i
c=a/b
puts(c)
rescue
   retry
else
    print("NO ANY EXCEPTION")
ensure
    print("Hello Ruby")    
end    


Raise:-

it is used to manually call the exception.

begin
puts("Enter First Number")
a=gets().to_i
if a<0
    raise
end    
rescue
   retry
else
    print("NO ANY EXCEPTION")
ensure
    print("Hello Ruby")    
end    

  

User Define Exception:-

using this we can create and call our own exception classes.

class NegativeException < StandardError
    attr_reader :reason
    def initialize(reason)
       @reason = reason
    end
 end

begin
puts("Enter First Number")
a=gets().to_i
if a<0
    raise NegativeException.new("")
end    
rescue
  print("Enter positive data")
else
    print("NO ANY EXCEPTION")
ensure
    print("Hello Ruby")    
end    


What is Thread?

Thread is a collection of lightweight processes, it is used to execute the program parallel. we can use a single thread and multithread both in ruby.


in a programming language, we prefer multithreading concepts for thread implementation.

using multithreading we can execute more than one process parallel under a multicore processor.


How to implement thread in the ruby program?

We create the object of thread class to implement thread

ref = Thread. new{statements}

How to start thread

ref. join()

How to sleep Thread

sleep(timeinterval)


Example of multithreading:-

def fun1()
    for i in 1..10
         puts("process #{i}")
         sleep(1)
    end    

end    

def fun2()
    for i in 100..110
         puts("process #{i}")
         sleep(1)
    end    

end  

t1 = Thread.new{fun1()}
t2 = Thread.new{fun2()}
t1.join()
t2.join()


Thread Synchronization`

count = 0
arr = []

10.times do |i|
   arr[i] = Thread.new {
      sleep(rand(0)/10.0)
      Thread.current["mycount"] = count
      count += 1
   }
end

arr.each {|t| t.join; print t["mycount"], ", " }
puts "count = #{count}"






Solve these programs in ruby language to improve your logical skills?

WAP to calculate the difference between two dates in the year, the date should be assigned on DDMMYYYY 

12052016
13062019
o/p  2019-2016  3

WAP to calculate the sum of all digits in date of birth?

WAP to Convert feet to inch and inch to feet?

WAP to convert km to meter?

WAP to convert decimal to binary?

WAP to calculate basic, ta, da, comm, pf,  HRA, Leave, number of leave will be entered by the users?

WAP to SWAP Two numbers using Third Variable?

WAP to SWAP WITHOUT UISNG Third Variable?

WAP to Calculate the Area of Triangle and Rectangle?

WAP to Reverse Five Digit Number without using Loop?

WAP to Calculate Addition of Complex Number?

WAP to calculate Simple Interest where rate and time will be constant and the principal will be an integer?

 WAP to calculate the area of a triangle, circle, and rectangle in the same program where the value of pi, the base of the triangle, and the height of the rectangle will be constant.
WAP to convert temperature from  Celsius to Fahrenheit?

Ternary Operator Based Program:-

WAP to check vowel and consonant using a ternary operator?
WAP to calculate the greatest number using a ternary operator in Python?
WAP to calculate the middle number using a ternary operator in Python?
WAP to check divisibility of the number that it is divisible by 3 and 5 or not?
WAP to check that salary is in income tax or not display the total amount and the taxable amount 
WAP to calculate electricity bill where unit price, total consumption will be entered by the user, if the bill is <400 then pay only 100 RS and above this 50% amount will be paid.

IF-Else Program List

Q) WAP to display the subject mark of the student which will be entered by the user's if the entered subject mark is eligible for grace then display mark including grace mark otherwise actual mark will display.

Q) WAP to check that the entered number is a one-digit number or above one-digit number, the number can be positive or negative?


2) WAP to Check Leap Year? 

3) WAP to check number is positive or negative?

Q) WAP to check that the entered number is a one-digit positive number, negative or two-digit positive number, or negative?

WAP to check greatest using four different numbers?

Q WAP to check divisibility of numbers from 3,5 and 9 with all combinations:-


Q) WAP to check that entered input is a numeric char or alphabet char?


Q WAP to display "YES" and "NO" when the user press 'y' and 'n'?

Q) WAP to Calculate Marksheet using five different subjects with the following condition.

1) all subject marks should be 0 to 100.
2) if only one subject mark is <33 then the student will be suppl.
3) if all subject marks are >=33 then percentage and division should be calculated.
4) if a student is suppl then five bonus marks can be applied to be pass and the result will be "pass by grace".
5) Display Grace Subject namedistinction subject name,suppl subject name, and failed subject name.


11) WAP to check whether the salary is in income tax criteria or not. if in income tax then display the income tax slab.


12)  WAP  TO CHECK THAT USERNAME AND PASSWORD ARE CORRECT OR NOT WHERE USERNAME IS YOUR FIRST NAME AND PASSWORD YOUR LASTNAME?

PROVIDE SEPARATE MESSAGES FOR INVALID USERNAME, INVALID PASSWORD, INVALID USERNAME, AND PASSWORD?







Tags

Post a Comment

150Comments

POST Answer of Questions and ASK to Doubt

  1. # WAP to check divisibility of the number that it is divisible by 3 and 5 or not?

    print "Enter any number: "
    num = gets.to_i

    if num%3 == 0 && num%5 == 0
    puts "the number is divisible by 3 and 5"
    elsif num%3 == 0
    puts "the number is divisible by 3"
    elsif num%5 == 0
    puts "the number is divisible by 5"
    else
    puts "the number is not divisible by 3 and 5"
    end

    ReplyDelete
  2. # WAP to check divisibility of the number that it is divisible by 3 and 5 or not? using ternary operator
    print "Enter any number: "
    num = gets.to_i
    cal = num%3 == 0 ? "number is divisible by 3" : num%5 == 0 ? "number is divisible by 5" : num%3 == 0 && num%5 == 0 ? "number is divisible by 3 and 5" : "not divisible 3 and 5"
    puts cal

    ReplyDelete
  3. # WAP to check divisibility of the number that it is divisible by 3 and 5 or not?

    print "Enter any number: "
    num = gets.to_i

    if num%3 == 0 && num%5 == 0
    puts "the number is divisible by 3 and 5"
    elsif num%3 == 0
    puts "the number is divisible by 3"
    elsif num%5 == 0
    puts "the number is divisible by 5"
    else
    puts "the number is not divisible by 3 and 5"
    end

    ReplyDelete
  4. # WAP to check vowel and consonant using a ternary operator?

    print "Enter year: "
    year = gets.to_i
    cal = year%400 == 0 || year%4 == 0 && year%100!=0 ? "Leap year" : "Not Leap year"
    puts cal

    ReplyDelete
  5. # range way calculate leap year
    print ("Enter starting year: ")
    s_year = gets.to_i
    print ("Enter ending year: ")
    e_year = gets.to_i
    for year in s_year..e_year do
    if year%400 == 0
    puts "#{year} leap year"
    elsif year%4 == 0 && year%100 != 0
    puts "#{year} leap year"
    else
    puts "#{year} Not a leap year"
    end
    end

    ReplyDelete
  6. # WAP to find max digit, second max digit in mobile number?

    print "Enter mobile number: "
    num = gets.to_i
    m = 0
    sm = 0
    while num!=0
    a = num%10
    num = num/10
    if m < a
    sm = m
    m = a
    elsif sm < a && num!=m
    sm = a
    end
    end
    puts "max number is: #{m}"
    puts "second max number is: #{sm}"

    ReplyDelete
  7. # WAP to find max digit, second max and third max digit in mobile number?
    print "Enter mobile number: "
    num = gets.to_i
    m = 0
    sm = 0
    tm = 0
    while num!=0
    mob = num%10
    if m < mob
    tm = sm
    sm = m
    m = mob
    elsif sm < mob
    tm = sm
    sm = mob
    elsif tm < mob
    tm = mob
    end
    num = num/10
    end
    puts "max number is: #{m}"
    puts "second max number is: #{sm}"
    puts "third max number is: #{tm}"

    ReplyDelete
  8. # WAP to calculate Simple Interest where rate and time will be constant and the principal will be an integer?

    print "Enter Principal: "
    prn = gets.to_i
    print "Enter Rate: "
    rate = gets.to_f
    print "Enter Time: "
    time = gets.to_f
    simpleinterest = (prn * rate * time)/100
    puts ("Simple Interest is: #{simpleinterest}")

    ReplyDelete
  9. # WAP to display the subject mark of the student which will be entered by the user's if the entered subject mark is eligible for grace then display mark including grace mark otherwise actual mark will display.

    print "Enter subject marks: "
    sub = gets.to_i
    if sub>=28 && sub<33
    grace = 33-sub
    puts "need of marks: #{grace}"
    sub += grace
    puts "my actual marks with grace: #{sub}"
    else
    puts "my actual marks without grace: #{sub}"
    end

    ReplyDelete
  10. # user input swap value
    print "Enter a value: "
    a = gets.to_i
    print "Enter b value: "
    b = gets.to_i
    z = a
    a = b
    b = z
    puts "a value: #{a}"
    puts "b value: #{b}"

    ReplyDelete
  11. # swap value using third variable

    a = 10
    b = 20
    # start swapping
    z = a
    a = b
    b = z
    puts "a value: #{a}"
    puts "b value: #{b}"

    ReplyDelete
  12. # swap value without using third variable

    print "Enter a value: "
    a = gets.to_i
    print "Enter b value: "
    b = gets.to_i
    a = a + b
    b = a - b
    a = a - b
    puts "a value: #{a}"
    puts "b value: #{b}"

    ReplyDelete
  13. # WAP to display "YES" and "NO" when the user press 'y' and 'n'?
    print "Enter n/y: "
    num = gets.chomp()
    if num == "y"
    puts "YES"
    elsif num == "n"
    puts "NO"
    else
    puts "invalid"
    end

    ReplyDelete
  14. # WAP to check vowel and consonant using a ternary operator?
    print "Enter char: "
    char = gets.chomp()
    cal = char == "a" || char == "e" || char == "i" || char == "o" || char == "u" ? "vowel" : "consonent"
    puts cal

    ReplyDelete
  15. # WAP to check that salary is in income tax or not display the total amount and the taxable amount
    print "Enter your amount: "
    num = gets.to_i
    sal = 50000
    tax = num-sal
    s = num<=sal ? "not taxable, total amount is: #{num}" : "taxable amount is: #{tax}, total amount is: #{tax+sal} "
    puts s

    ReplyDelete
  16. # convert km to meter

    print "Enter km: "
    km = gets.to_f
    meter = (km * 1000).to_f
    puts "convert km to meter: #{meter}m"

    ReplyDelete
  17. # convert meter to km

    print "Enter meter: "
    meter = gets.to_f
    km = (meter / 1000).to_f
    puts "convert meter to km: #{km}km"

    ReplyDelete
  18. # true and false using ternary operator

    print "Enter a value: "
    a = gets.to_i
    puts a<=20 ? true : false

    ReplyDelete
  19. # wap to calculate factorial of any entered number?

    print "Enter factorial number: "
    num = gets.to_i
    fact = 1
    if num == 0
    puts "invalid!, could not find the factorial of one"
    else
    i = 1
    while i<=num
    fact = fact*i
    i = i+1
    puts "The factorial number #{num} is: #{fact}"
    end
    end

    ReplyDelete
  20. # feet to inch

    print "Enter feet: "
    feet = gets.to_f
    inch = 12 * feet
    puts "convert feet into inch: #{inch}"

    ReplyDelete
  21. # inch to feet

    print "Enter inch: "
    inch = gets.to_f
    feet = inch / 12
    puts "Convert into into feet: #{feet}"

    ReplyDelete
  22. print "Temperature value in degree Celsius: "
    celsius = gets.to_f
    Fahrenheit = (celsius * 1.8)+32
    puts "The #{celsius} degree Celsius is equal" +
    " to: #{Fahrenheit} Fahrenheit"

    ReplyDelete
  23. # 1 way to check vowel and consonent using case statement

    print "Enter Char: "
    char = gets.chomp()
    case char
    when "a"
    puts "vowel1"
    when "e"
    puts "vowel2"
    when "i"
    puts "vowel3"
    when "o"
    puts "vowel4"
    when "u"
    puts "vowel5"
    else
    puts "consonent"
    end

    ReplyDelete
  24. # area of triangle

    print "Enter a: "
    a = gets.to_f
    print "Enter b: "
    b = gets.to_f
    print "Enter c: "
    c = gets.to_f
    s = (a+b+c)/2
    area = (s*(s-a)*(s-b)*(s-c))**0.5
    puts "the area of triangle #{area}"

    ReplyDelete
  25. # area of rectangle

    print "Enter height: "
    height = gets.to_f
    print "Enter width: "
    width = gets.to_f
    area = height*width
    puts "the area of rectangle: #{area}"

    ReplyDelete
  26. # area of circle

    PI = 3.14
    print "Enter radius of a circle: "
    r = gets.to_f
    area = PI * r * r
    puts "the area of rectangle: #{area}"

    ReplyDelete
  27. # addition of complex number

    a = Complex(6+7i)
    b = Complex(7+8i)
    sum = a+b
    puts "Addition of complex number is: #{sum}"

    ReplyDelete
  28. # add two number without using + operator

    print "Enter first number: "
    a = gets.to_i
    print "Enter second number: "
    b = gets.to_i
    sum = a-(-b)
    puts "add two number: #{sum}"

    ReplyDelete
  29. # WAP to calculate electricity bill where unit price, total consumption will be entered by the user, if the bill is <400 then pay only 100 RS and above this 50% amount will be paid using ternary operator

    print "Enter Unit price per unit: "
    a = gets.chomp().to_i
    print "Enter starting unit: "
    from = gets.chomp().to_i
    print "Enter ending unit: "
    to = gets.chomp().to_i
    consumption = to - from
    total = a*consumption
    puts "Electricity bill from #{from} to #{to}: #{consumption}"

    cal = total<400 ? "pay only 100rs" : "pay actual bill with 50% discount: #{total/2}"
    puts cal

    ReplyDelete
  30. # WAP to calculate electricity bill where unit price, total consumption will be entered by the user, if the bill is <400 then pay only 100 RS and above this 50% amount will be paid.

    print "Enter Unit price per unit: "
    a = gets.chomp().to_i
    print "Enter starting unit: "
    from = gets.chomp().to_i
    print "Enter ending unit: "
    to = gets.chomp().to_i
    cal = to - from
    total = a * cal
    puts "Electricity bill from #{from} to #{to}: #{cal}"
    if total<400
    puts "pay only 100rs"
    else
    puts "pay actual bill with 50% discount: #{total/2}"
    end

    ReplyDelete
  31. # divisible 3 and 5 using until loop

    print "Enter number: "
    num = gets.to_i
    x = 1
    until x >= num
    if x%3 == 0 && x%5 == 0
    puts "#{x} is divisible by 3 and 5"
    elsif x%3 == 0
    puts "#{x} is divisible by 3"
    elsif x%5 == 0
    puts "#{x} is divisible by 5"
    else
    puts "#{x} is not divisible by 3 and 5"
    end
    x += 1
    end

    ReplyDelete
  32. # table print using until loop

    print "enter any number: "
    num = gets.to_i
    x = 1
    until x >= 11
    t = num*x
    puts t
    x += 1
    end

    ReplyDelete
  33. # WAP to print 1 to 5 and 5 to 1 again 1 to 5 and 5 to 1 using a until loop?

    y = 1
    until y >= 21
    if y <= 5
    puts y
    elsif y <= 10
    puts (11 - y)
    elsif y <=15
    puts (y - 10)
    else
    puts (21 - y)
    end
    y += 1
    end

    ReplyDelete
  34. # any number increment decrment using until loop

    print "Enter any number: "
    num = gets.to_i
    x = 1
    until x > num
    if x <= 5
    puts x
    else
    puts (num + 1- x)
    end
    x += 1
    end

    ReplyDelete
  35. # user input check even odd using while loop

    print "Enter number: "
    num = gets.to_i

    z = 0
    while z <= num
    if z.even?
    puts "#{z} is even"
    else
    puts "#{z} is odd"
    end
    z += 1
    end

    ReplyDelete
  36. # WAP to check divisibility of numbers from 3,5 with all combinations using for loop

    print "Enter starting number: "
    num1 = gets.to_i
    print "Enter ending number: "
    num2 = gets.to_i
    for x in num1..num2
    if x%3 == 0 && x%5 == 0
    puts "#{x} is divisible by 3 and 5"
    elsif x%3 == 0
    puts "#{x} is divisible by 3"
    elsif x%5 == 0
    puts "#{x} is divisible by 5"
    else
    puts "#{x} is not divisible by 3 and 5"
    end
    end

    ReplyDelete
  37. # using for loop next and break
    for x in 1..10
    if x == 5
    next
    end
    if x == 8
    break
    end
    print x, " "
    end
    puts

    ReplyDelete
  38. # positive or negative ternary operator

    print "Enter number: "
    num = gets.to_i
    sum = num>=0 ? "positive" : "negative"
    puts sum

    ReplyDelete
  39. #WAP to Check Leap Year.


    puts "enter year"
    year=gets().to_i
    if year%4==0 && year%100!=0 || year%400==0
    puts "leap year"
    else
    puts "not leap year"
    end

    ReplyDelete
  40. # WAP to check number is positive or negative?

    puts "enter number"
    num=gets().to_i
    if num>0
    puts "this is positive number"
    else
    puts "this is negative number"

    end

    ReplyDelete
  41. WAP to check the greatest number?

    a=10
    b=20
    c=34
    d=23
    if a>b && a>c && a>d
    puts "a is greatest"
    elsif b>c && b>d
    puts "b is greatest"
    elsif c>d
    puts "c is greatest"
    else
    puts "d is greatest"

    end

    ReplyDelete
  42. WAP to check greatest using four different numbers?

    a=10
    b=20
    c=34
    d=23
    if a>b && a>c && a>d
    puts "a is greatest"
    elsif b>c && b>d
    puts "b is greatest"
    elsif c>d
    puts "c is greatest"
    else
    puts "d is greatest"

    end

    ReplyDelete
  43. WAP to check that entered number is one digit negative number or a positive number?
    puts "enter number"
    num=gets().to_i
    if num>0 && num<=9
    puts "this is one digit number"
    else
    puts "this is two digit number"

    end

    ReplyDelete
  44. WAP to check divisibility of number from 3,5 and 7 with all combination:-

    puts "enter num"
    num=gets().to_i
    if num%3==0
    puts "num is divisile by 3"
    elsif num%5==0
    puts "num is divisile by 5"
    elsif num%7==0
    puts "num is divisile by 7"
    else
    puts "this is not by anyone"

    end

    ReplyDelete
  45. WAP to display "YES" and "NO" when the user press 'y' and 'n'?

    puts "enter char"
    char=gets().chomp
    if char=='y'
    puts "yes"
    elsif char=='n'
    puts "no"
    else
    puts "this is not yes or no"

    end

    ReplyDelete
  46. WAP to check that entered char is vowel and consonant without using or operator?

    puts "enter char"
    char=gets().chomp
    if char=='a'
    puts "this is vowel"
    elsif char=='b'
    puts "this is vowel"
    elsif char=='c'
    puts "this is vowel"
    elsif char=='d'
    puts "this is vowel"
    elsif char=='e'
    puts "this is vowel"
    else
    puts "this is consonent"

    end

    ReplyDelete
  47. WAP to check that salary is in income tax criteria or not. if in income tax then display income tax slab.
    puts "enter salary"
    salary=gets().to_i
    if salary<250000
    puts "tax is not payable"

    else
    puts "tax is payable"
    end

    ReplyDelete
  48. WAP TO CHECK THAT USERNAME AND PASSWORD BOTH ARE CORRECT OR NOT WHERE USERNAME IS YOUR FIRST NAME AND PASSWORD YOUR LASTNAME?

    puts "enter first name"
    fname=gets().chomp
    puts "enter last name"
    lname=gets().chomp
    if fname=='abhi' && lname=='kumar'
    puts "valid username or password"
    else
    puts "invalid username or password"
    end

    ReplyDelete
  49. # WAP to check the greater number using Ternary Operator?
    puts "enter first number"
    a=gets().to_i
    puts "enter second number"
    b=gets().to_i
    res = a>b ? "a is greater " : "b is greater"
    puts res

    ReplyDelete
  50. #WAP to check that salary is in income tax or not display the total amount and the taxable amount

    puts "enter your salary"
    salary=gets().to_i
    res = salary<=250000 ? "tax is not payable" : "tax is payable"
    puts res

    ReplyDelete
  51. #WAP to check divisibility of number that it is divisible by 3 and 5 or not?

    puts "enter the number"
    num = gets.to_i
    res = num%3==0 && num%5==0 ? "num is divisible" : "num is not divisible"
    puts res

    ReplyDelete
  52. #WAP to check vowel and consonant using a ternary operator?

    puts "enter the char"
    s=gets().chomp
    res= s=='a' || s=='e' || s=='i' || s=='o' || s=='u' ? "this is vowel" : "this is consonent"
    puts res

    ReplyDelete
  53. #WAP to check leap year using a ternary operator in ruby?

    puts "enter the year"
    year=gets().to_i
    s = year%4==0 && year%100!=0 || year%400==0 ? "leap year" : "not leap year"
    puts s

    ReplyDelete
  54. #WAP to check divisibility of number that it is divisible by 3 and 5 or not?


    puts "enter the number"
    num=gets().to_i
    res = num%3==0 ? "this is divisible by num" : "this is not divisible by num" && num%5==0 ? "this is divisible by num" : "this is not divisible by num "
    puts res

    ReplyDelete
  55. # marksheet calculate program

    print "Enter math marks: "
    m = gets.to_i
    print "Enter physics marks: "
    py = gets.to_i
    print "Enter science marks: "
    s = gets.to_i
    print "Enter hindi marks: "
    h = gets.to_i
    print "Enter english marks: "
    e = gets.to_i

    # all sub should be 0 to 100 marks
    if (m >= 0 && m <= 100) && (py >= 0 && py <= 100) && (s >= 0 && s <= 100) && (h >= 0 && h <= 100) && (e >= 0 && e <= 100)

    # all sub should >33 marks if one sub marks is <33 and >28 stu is suppli then so other all sub add bonus then student will be pass
    sub = ''
    grace = 0
    if m < 33
    sub += 'Math '
    grace = m
    end
    if py < 33
    sub += 'Pysics '
    grace = py
    end
    if s < 33
    sub += 'Science '
    grace = s
    end
    if h < 33
    sub += 'Hindi '
    grace = h
    end
    if e < 33
    sub += 'English '
    grace = e
    end
    # distinction subject
    dist = ''
    if m >= 75
    dist += "Math "
    end
    if py >= 75
    dist += "Physics "
    end
    if s >= 75
    dist += "Science "
    end
    if h >= 75
    dist += "Hindi "
    end
    if e >= 75
    dist += "English "
    end
    # percentage and grace marks calculate
    if grace>=28 && grace <= 33
    cal = 33-grace
    grace += cal
    per = ((m+py+s+h+e+cal)/5).to_f
    puts "Supplementary in #{sub} Subject, form #{cal} number then" +
    " add bonus so, student will be #{grace} marks."
    elsif m >= 33 && s>= 33 && py >= 33 && h >= 33 && e >=33
    per = ((m+py+s+h+e)/5).to_f
    else
    puts "Fail in #{sub} Subject."
    exit
    end
    # division calculate
    if per < 33
    puts %{Pass in third division #{per}% and Distinction subject #{dist}.} # no need of single and double quotes 1 way
    elsif per < 50
    puts %Q{Pass in second division #{per}% and Distinction subject #{dist}.} # 2 way
    else
    puts %{Pass in first division #{per}% and Distinction subject #{dist}.}
    end

    else
    puts %{All sub should be 0 to 100 marks}
    end

    ReplyDelete
  56. # WAP to mange ATM operation in simple logic

    puts "Add to card"
    i = 1
    while i<=3
    print "Enter 4-digit pin no "
    pin = gets.to_i
    pin1 = 2022
    if pin == pin1
    puts "correct your pin no"
    bal = 500
    i = 0
    while i<2
    puts "Press menu Button"
    puts "="*30
    puts "C for Credit\tB for check balance\nD for Debit\tR for Repeat operation\nE for the exit"
    press = gets.chomp()
    if press == "c"
    puts "Enter amount"
    am = gets.to_i
    puts "your total amount #{bal+am}"
    elsif press == 'b'
    puts "your total amount #{bal}"
    elsif press == 'd'
    puts "Enter withdraw amount"
    am1 = gets.to_i
    puts "your remaining amount #{bal-am1}"
    elsif press == 'r'
    puts "Repeat operation"
    elsif press == 'e'
    break
    else
    puts "invalid input"
    end
    end
    break
    else
    puts "Invalid pin no!, try again[y/n] "
    try = gets.chomp()
    if try == "y"
    end
    if try == 'n'
    puts "Thanks for using atm"
    break
    end
    end
    i += 1
    if i == 4
    puts "Sorry! only three times using PIN!"
    exit
    end
    end

    ReplyDelete
  57. # nested_for_loop
    #12345
    #12345
    #12345
    #12345
    #12345

    for x in 1..5
    for y in 1..5
    print y
    end
    puts
    end
    puts

    ReplyDelete
  58. #54321
    #54321
    #54321
    #54321
    #54321
    for x in 1..5
    for y in 5.downto(1)
    print y
    end
    puts
    end
    puts

    ReplyDelete
  59. #11111
    #22222
    #33333
    #44444
    #55555

    for x in 1..5
    for y in 1..5
    print x
    end
    puts ()
    end
    puts

    ReplyDelete
  60. 55555
    44444
    33333
    22222
    11111

    for x in 5.downto(1)
    for y in 5.downto(1)
    print x
    end
    puts ()
    end
    puts

    ReplyDelete
  61. 2 3 4 5
    4 6 8 10
    6 9 12 15
    8 12 16 20
    10 15 20 25
    12 18 24 30
    14 21 28 35
    16 24 32 40
    18 27 36 45
    20 30 40 50

    # column type table print
    for i in 1..10
    for j in 2..5
    z = j*i
    print z, "\t "
    end
    puts ()
    end
    puts

    ReplyDelete
  62. 2 4 6 8 10 12 14 16 18 20
    3 6 9 12 15 18 21 24 27 30
    4 8 12 16 20 24 28 32 36 40
    5 10 15 20 25 30 35 40 45 50

    # table print row type
    for i in 2..5
    for j in 1..10
    z = j*i
    print z, " "
    end
    puts ()
    end
    puts

    ReplyDelete
  63. 1
    2 2
    3 3 3
    4 4 4 4
    5 5 5 5 5

    # trianle shape
    for x in 1..5
    for y in 1..x
    print x, " "
    end
    puts ()
    end
    puts

    ReplyDelete
  64. 12345
    1234
    123
    12
    1
    # start prog

    for x in 5.downto(1)
    for y in 1..x
    print y
    end
    puts ()
    end
    puts

    ReplyDelete
  65. 54321
    5432
    543
    54
    5

    for x in 1..5
    for y in 5.downto(x)
    print y
    end
    puts ()
    end
    puts

    ReplyDelete
  66. 1
    12
    123
    1234
    12345

    for x in 5.downto(1)
    for y in 1..6-x
    print y
    end
    puts
    end
    puts

    ReplyDelete
  67. 11111
    2222
    333
    44
    5

    for x in 1..5
    for y in 1..6-x
    print x
    end
    puts ()
    end
    puts

    ReplyDelete
  68. 5
    44
    333
    2222
    11111

    for x in 5.downto(1)
    for y in 1..6-x
    print x
    end
    puts ()
    end
    puts

    ReplyDelete
  69. ij
    11
    22
    33
    44
    55

    puts "ij"
    for i in 1..5
    ch = 2
    for j in 1..2
    if i%2 == 0 && i%4 != 0
    print ch
    else
    print i
    end
    end
    puts
    end

    ReplyDelete
  70. ij
    15
    24
    33
    42
    51

    puts "ij"
    for i in 1..5
    for j in 1..2
    end
    print i
    j = 6-i
    print j
    puts
    end

    ReplyDelete
  71. *
    ***
    *****
    ***
    *
    # star pattern
    ch = 2
    for i in 1..5
    if i <= 3
    for k in 1..5-i
    print " "
    end
    for j in 1..i*2-1
    print "*"
    end
    else
    for k in (5-i)..3
    print " "
    end
    for j in 1..2*(ch)-1
    print "*"
    end
    ch -= 1
    end
    puts
    end

    ReplyDelete
  72. *
    * *
    * * *
    * * * *
    * * * * *
    for x in 1..5
    for y in 1..x
    print "*", " "
    end
    puts ""
    end

    ReplyDelete
  73. *****
    ****
    ***
    **
    *
    for x in 1..5
    ch = "*"
    for y in 1..6-x
    print ch
    end
    puts
    end

    ReplyDelete
  74. A B C D E
    A B C D
    A B C
    A B
    A

    for i in 1..5
    ch = 65
    for j in 1..6-i
    print (ch.chr), " "
    ch += 1
    end
    puts
    end
    puts

    ReplyDelete
  75. A
    A B
    A B C
    A B C D
    A B C D E

    for x in 5.downto(1)
    ch = 65
    for y in 1..6-x
    print (ch.chr), " "
    ch += 1

    end
    puts
    end
    puts

    ReplyDelete
  76. @
    @ ?
    @ ? >
    @ ? > =
    @ ? > = <

    for x in 5.downto(1)
    ch = 64
    for y in 1..6-x
    print (ch.chr), " "
    ch -= 1
    end
    puts
    end
    puts

    ReplyDelete
  77. E D C B A
    E D C B
    E D C
    E D
    E

    for x in 69.downto(65-1)
    ch = 69
    for y in 65..x
    print (ch.chr), " "
    ch -= 1
    end
    puts
    end

    ReplyDelete
  78. A B C D E
    a b c d
    A B C
    a b
    A

    for x in 69.downto(65)
    ch = 97
    for y in 65..x
    if x%2 == 0
    print (ch.chr), " "
    ch += 1
    else
    print (y.chr), " "

    end
    end
    puts
    end

    ReplyDelete
  79. A
    a b
    A B C
    a b c d
    A B C D E

    for x in 65..69
    ch = 97
    for y in 65..x
    if x%2 == 0
    print (ch.chr), " "
    ch += 1
    else
    print (y.chr), " "
    end
    end
    puts
    end

    ReplyDelete
  80. A a B b C
    A a B b
    A a B
    A a
    A
    for i in 1..5
    ch = 65
    for j in 1..6-i
    if j%2 == 0
    print (ch.to_i++32).chr, " "
    ch += 1
    else
    print ch.chr, " "
    end
    end
    puts
    end

    ReplyDelete
  81. 1 0 0 1 0
    1 0 0 1
    1 0 0
    1 0
    1

    for x in 1..5
    ch = 1
    ch1 = 0
    for y in 1..6-x
    if y%2 == 0
    print (ch1), " "
    ch1 = 1
    else
    print (ch), " "
    ch = 0
    end
    end
    puts
    end

    ReplyDelete
  82. 1 2 3 4 5
    5 4 3 2
    1 2 3
    5 4
    1
    for i in 1..5
    for j in 1..6-i
    if i%2 == 0
    print (6-j), " "
    else
    print j, " "
    end
    end
    puts
    end

    ReplyDelete
  83. WAP to find fibonacci series.

    a = 0
    b = 1
    for i in 0..11
    c = a+b
    puts c
    a=b
    b=c
    end

    ReplyDelete
  84. WAP TO FIND MAX SECOND MAX AND THIRD MAX NUMBER.

    puts "enter mobile number"
    mobile=gets().to_i
    m=0
    sm=0
    tm=0
    while mobile!=0
    num=mobile%10
    if m<num
    tm=sm
    sm=m
    m=num
    elsif sm<num
    tm=sm
    sm=num
    elsif tm<num
    tm=num

    end
    mobile=mobile/10


    end
    puts m, sm, tm

    ReplyDelete
  85. WAP TO FIND MAX AND SECOND MAX NUMBER OF ANY NUMBER.

    puts "enter number"
    num=gets().to_i
    m=0
    sm=0
    while num!=0
    a=num%10
    num=num/10
    if m<a
    sm=m
    m=a
    elsif sm<a && num!=m
    sm=a
    end

    end
    puts "the max digit is #{m}, and the second digit number is #{sm}"

    ReplyDelete
  86. WAP TO SUM OF ODD NUMBER.

    puts "enter number"
    num=gets().to_i
    if num%2!=0
    for i in 1..11
    k = num*i
    puts k
    end
    else
    puts "enter only odd number"


    end

    ReplyDelete
  87. WAP TO SUM OF EVEN NUMBER.

    puts "enter number"
    num=gets().to_i
    if num%2==0
    for i in 0..10
    k = num*i
    puts k
    end
    else
    puts "enter only even number"

    end

    ReplyDelete
  88. # separate message enter username password invalid and try again only two times in do-while loop
    i = 1
    loop do
    print "Enter Username: "
    uname = gets.chomp()
    print "Enter Password: "
    pass = gets.chomp()
    if uname == "reshu"
    if pass == "singh"
    puts "Correct Username & Password "
    break
    else
    puts "Invalid password"
    print "try again [y/n]: "
    num = gets.chomp
    if num == "y"
    else
    break
    end
    end
    else
    puts "Invalid username"
    print "try again [y/n]: "
    num = gets.chomp
    if num == "y"
    else
    break
    end
    i += 1
    if i == 3
    puts "Sorry, only two times use"
    break
    end
    end
    end

    ReplyDelete
  89. A B C D E
    A B C D
    A B C
    A B
    A

    ANSWER:-

    for i in 1..5
    c=65
    for j in 1..6-i
    print (c.chr)
    c=c+1
    end
    puts()
    end

    ReplyDelete
  90. 10010
    1001
    100
    10
    1

    ANSWER:-

    for i in 1..5
    a=1
    b=0
    for j in 1..6-i
    if j%2==0
    print b
    b =1
    else
    print a
    a=0
    end
    end
    puts()
    end

    ReplyDelete
  91. 12345
    5432
    123
    54
    1

    ANSWER:-

    for i in 1..6
    for j in 1..6-i
    if i%2==0
    print 6-j
    else
    print j
    end
    end
    puts()
    end

    ReplyDelete
  92. 1
    12
    123
    1234
    12345

    ANSWER:-

    for i in 1..5
    for j in 1..i
    print j
    end
    puts()
    end

    ReplyDelete
  93. A
    AB
    ABC
    ABCD
    ABCDE

    ANSWER:-

    for i in 1..5
    c=65
    for j in 1..i
    print (c.chr)
    c=c+1
    end
    puts()
    end

    ReplyDelete
  94. WAP TO CALCULATE FACTORIAL .

    puts "enter number to calculate factorial"
    num=gets().to_i
    i=num
    f=1
    while i>=1
    f=f*i
    i=i-1

    end
    puts "factorial is #{f}"

    ReplyDelete
  95. *
    **
    ***
    ****
    *****
    ANSWER:-
    for i in 1..5
    for j in 1..i
    print "*"
    end
    puts()
    end

    ReplyDelete
  96. *
    * *
    * * *
    * * * *
    * * * * *
    * * * * * *
    * * * * * * *
    * * * * * * * *
    * * * * * * * * *
    * * * * * * * * * *

    ANSWER:-

    for i in 0..10
    print " "*(10-i), "* "*i, "\n"
    end

    ReplyDelete
  97. *
    * *
    * * *
    * * * *
    * * * * *
    * * * * * *
    * * * * * * *
    * * * * * * * *
    * * * * * * * * *
    * * * * * * * * * *

    answer:-

    puts "enetr number"
    rows=gets().to_i
    for i in 0..rows
    print "* "*i, "\n"

    end

    ReplyDelete
  98. WAP TO REVERSE ANY NUMBER.

    puts "enter number"
    num=gets().to_i
    s = ""
    while num!=0
    a=num%10
    num=num/10
    s = s + a.to_s
    end
    puts s

    ReplyDelete
  99. A a B b C
    A a B b
    A a B
    A a
    A


    for i in 1..5
    ch = 65
    for j in 1..6-i
    if j%2 == 0
    print (ch.to_i++32).chr, " "
    ch += 1
    else
    print ch.chr, " "
    end
    end
    puts
    end

    ReplyDelete
  100. map() method :- map() is a array class which return a new array containing the value returned by the block.
    The main use of map is transform data.

    Q. multiply each element of an array by 2.

    array = [12,34,56,77,88,99]
    print array.map { |num| num*2 }, "\n"

    [24, 68, 112, 154, 176, 198]

    ReplyDelete
  101. include method:-The include? method checks to see if the argument given is included in the array.

    a = [1,2,3,4,5,6]
    print a.include?(5), "\n"

    output:- true

    ReplyDelete
  102. concat():- concat() is a Array class method which returns the array after appending the two arrays together.

    a = [23,4,5,6,7,8]
    b = [4.56,77,88,75]
    c = [23,45,66,77,88]

    puts " combining a and b : #{a.concat(b)}"
    puts " combining b and c : #{b.concat(c)}"
    puts "combining c and a : #{c.concat(a)}"


    combining a and b : [23, 4, 5, 6, 7, 8, 4.56, 77, 88, 75]
    combining b and c : [4.56, 77, 88, 75, 23, 45, 66, 77, 88]
    combining c and a : [23, 45, 66, 77, 88, 23, 4, 5, 6, 7, 8, 4.56, 77, 88, 75]

    ReplyDelete
  103. # 2) WAP to find the max and second max and third max element in an array?

    arr = [1,9,6,7,4,3,2,5]
    for i in 0...arr.length
    for j in i+1...arr.length
    if arr[i] < arr[j]
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
    end
    end
    end
    print "sorting Array: #{arr}"
    puts
    print "Find largest number: #{arr[0]}"
    puts
    print "Find second largest number: #{arr[1]}"
    puts
    print "Find third largest number: #{arr[2]}"

    ReplyDelete
  104. # 6) WAP to display prime elements in the array?

    arr = [45,67,2,45,78,9,8,47,13]

    for i in 0...arr.length
    c=0
    for j in 2...arr[i]
    if arr[i]%j == 0
    c = 1
    break
    end
    end
    if c == 0 && arr[i]>1
    puts arr[i]
    end
    end

    ReplyDelete
  105. # Element sort asending order
    print "Enter array size: "
    size = gets.to_i
    arr = []
    for j in 0...size
    print "Enter element: "
    ele = gets.to_i
    arr.append(ele)
    end
    for i in 0...size
    for j in 0...(size-i-1)
    if arr[j] > arr[j+1]
    t = arr[j]
    arr[j] = arr[j+1]
    arr[j+1] = t
    end
    end
    end
    print "Element sort asending order: #{arr}"

    ReplyDelete
  106. # Element sort decending order

    arr = [12,89,6,11,6,4,78]
    for i in 0...arr.length
    for j in i+1...arr.length
    if arr[i] < arr[j]
    t = arr[i]
    arr[i] = arr[j]
    arr[j] = t
    end
    end
    end
    puts
    print "Element sort decending order: #{arr}"

    ReplyDelete
  107. # Multiplication of two matrix
    puts "Multiplication of two matrix"
    a = [[1,4,6],[2,8,78]]
    b = [[67,90,87],[3,45,21]]
    c = [[0,0,0],[0,0,0]]
    for i in 0...a.length
    for j in 0...a[0].length
    c[i][j] = a[i][j] * b[i][j]
    end
    end
    for arr in c
    print arr
    puts
    end

    ReplyDelete
  108. # Addition of two matrix
    puts "Addition of two matrix"
    a = [[1,4,6],[2,7,5]]
    b = [[7,0,3],[3,2,1]]
    c = [[0,0,0],[0,0,0]]
    for i in 0...a.length
    for j in 0...a[0].length
    c[i][j] = a[i][j] + b[i][j]
    end
    end
    print c

    ReplyDelete
  109. # 4) WAP to calculate compound interest using no return type function.
    def compound_interest
    print "Enter Principal amount: "
    pr = gets.to_f
    print "Enter Annual nominal interest rate as a decimal: "
    rate = gets.to_f
    print "Enter number of compounding periods per unit of time: "
    n = gets.to_i
    print "Enter time in decimal years: "
    t1 = gets.to_i
    # e.g., time in decimal years 6 months is calculated as 0.5 years
    t = t1/2.to_f

    # Annual nominal interest rate as a decimal calculate
    r = rate/100

    # formula based calculate compound_interest
    cal = pr*(1+r/n)**(n*t)
    puts "The total amount accrued," +
    " principal plus interest," +
    " with compound interest on a principal" +
    " of $#{pr} at a rate of #{rate} per year compounded #{n} times per year" +
    " over #{t} years is $#{cal}."
    end
    compound_interest() # calling method

    ReplyDelete
  110. # 3) WAP to create a salary calculator using no return type function

    def salary
    print "Enter basic: "
    basic = gets.to_i
    print "Enter Travel Allowance: "
    ta = gets.to_i
    print "Enter Dearness Allowance: "
    da = gets.to_i
    print "Enter Commission: "
    comm = gets.to_i
    print "Enter Provident Fund: "
    pf = gets.to_i
    print "Enter House Rent Allowance: "
    hra = gets.to_i
    print "Enter total leave: "
    leave = gets.to_i

    # calculation
    lv = ta+da+comm
    lv1 = basic/30
    lvdeduction = lv1*(30-leave)
    total = lvdeduction+lv-pf-hra
    puts "Total salary in-hand #{total}"
    end
    salary()

    ReplyDelete
  111. # 3) Create a Sorting program using parametrized function?
    def sort_method(*arr)
    for i in 0...arr.length
    for j in i+1...arr.length
    if arr[i] > arr[j]
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
    end
    end
    end
    arr.each do |k|
    print k, " "
    end
    end
    sort_method(12,89,6,11,8,1,2)

    ReplyDelete
  112. WAP to create complete biodata for a marriage proposal?


    f = File.new("biodata.txt","w")
    if f
    puts("Enter your name")
    name=gets
    puts("Enter your father name ")
    name1=gets
    puts "enter mobile number"
    num=gets
    puts "enter your date of birth"
    dob=gets
    puts "enter occupation"
    occupation=gets
    puts "manglik"
    mangkil=gets
    puts "enter zodiac"
    zodiac=gets
    puts "what is your education"
    education=gets
    puts "address"
    add=gets
    f.syswrite("name is #{name}
    and father name is #{name1}
    and mobile number is #{num}
    and dob is #{dob}
    and occupation is #{occupation}
    and mangkil #{mangkil}
    and zodiac is #{zodiac}
    and eduactiob is #{education}
    and address is #{add}")
    end

    ReplyDelete
  113. WAP to perform the addition of two numbers and write the output of addition under file?

    f = File.new("addition.txt", "w+")
    puts "enter first number"
    num1=gets().to_i
    puts "enter second number"
    num2=gets().to_i
    num3=num1+num2
    f.syswrite("addition is #{num3}")

    ReplyDelete
  114. WAP to create horoscope software?

    f = File.new("horoscope.txt", "w")
    if f
    puts "aries"
    aries=gets
    puts "Taurus"
    taurus=gets
    puts "Cancer"
    cancer=gets
    puts "Leo"
    leo=gets
    puts "Virgo"
    virgo=gets
    puts "Libra"
    libra=gets
    puts "scorpio"
    scorpio=gets
    puts "Sagittarius"
    sagittarius=gets
    puts "Capricon"
    capricon=gets
    puts "Aquarius"
    aquarius=gets
    puts "Pisces"
    pisces=gets
    f.syswrite("aries:- #{aries}
    Taurus:- #{taurus}
    Cancer:- #{cancer}
    Leo:- #{leo}
    Virgo:- #{virgo}
    Libra:- #{libra}
    scorpio:-#{scorpio}
    Sagittarius:- #{sagittarius}
    Capricon:- #{capricon}
    Aquarius:- #{aquarius}
    pisces:- #{pisces}")
    end

    ReplyDelete
  115. # 3) WAP to create horoscope software?
    # write and read file
    f = File.open("horoscope.txt", "r+")

    a = "Arise:- The first sign of the zodiac, Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition"
    f.puts a

    t = "Taurus:- Taurus is an earth sign represented by the bull."
    f.puts t

    g = "Gemini:- Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself."
    f.puts g

    l = "Libra:- Libra is obsessed with symmetry and strives to create equilibrium in all areas of life"
    f.puts l

    # read file
    f.seek(0)
    data = f.read()
    puts "Aries\tTaurus\nGemini\tLibra"
    print "Enter your horoscope: "
    hero = gets.chomp()
    if hero == "Arise" || hero == "a"
    puts a
    elsif hero == "Taurus" || hero == "t"
    puts t
    elsif hero == "Gemini" || hero == "g"
    puts g
    elsif hero == "Libra" || hero == "l"
    puts l
    else
    puts "sorry! No horoscope available"
    end
    f.close

    ReplyDelete
  116. # horoscope
    # write file
    f = File.open("horoscope1.txt", "w")
    puts "Aries\tTaurus\nGemini\tLibra"
    print "enter your horoscope: "
    hero = gets.chomp()
    if hero == "Arise" || hero == "a"
    f.write "The first sign of the zodiac, Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition"
    elsif hero == "Taurus" || hero == "t"
    f.write "Taurus is an earth sign represented by the bull."
    elsif hero == "Gemini" || hero == "g"
    f.write "Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself."
    elsif hero == "Libra" || hero == "l"
    f.write "Libra is obsessed with symmetry and strives to create equilibrium in all areas of life"
    end
    f.close
    # read file
    puts File.read("horoscope1.txt") # 1 way read file
    puts IO.readlines("horoscope1.txt") # 2 way read file

    ReplyDelete
  117. # write and read file
    f = File.open("horoscope1.txt", "w+")
    puts "Aries\tTaurus\nGemini\tLibra"
    print "enter your horoscope: "
    hero = gets.chomp()
    if hero == "Arise" || hero == "a"
    f.write "The first sign of the zodiac, Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition"
    elsif hero == "Taurus" || hero == "t"
    f.write "Taurus is an earth sign represented by the bull."
    elsif hero == "Gemini" || hero == "g"
    f.write "Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself."
    elsif hero == "Libra" || hero == "l"
    f.write "Libra is obsessed with symmetry and strives to create equilibrium in all areas of life"
    end
    f.seek(0)
    data = f.read()
    puts data
    f.close

    ReplyDelete
  118. # 1) Count total vowel and consonant in String?

    print "Enter string: "
    s = gets.chomp()
    count = 0
    cnt = 0
    for i in 0...s.length
    if s[i] == 'a' || s[i]=='e' || s[i] =='i' || s[i]=='o' || s[i]=='u'
    count += 1
    elsif s[i] != 'a' || s[i]=='e' || s[i] =='i' || s[i]=='o' || s[i]=='u'
    cnt += 1
    end
    end
    puts "Number of vowels: #{count}"
    puts "Number of consonents: #{cnt}"

    ReplyDelete
  119. # 6) WAP to validate email?

    print "enter email id: "
    str = gets.to_s
    c = 0
    ch = 0
    for i in 0...str.length
    if str[i] == "@" || str[i] == "."
    c += 1
    else
    ch += 1
    end
    end
    if c == 2 && str.length>1
    puts "Valid"
    else
    puts "Not valid"
    end
    puts "Special charecter count #{c}."
    puts "All charecter count but not incude special charecter #{ch}."
    puts

    ReplyDelete
  120. # 2 condition use in valid email
    print "Enter email ID: "
    s = gets.chomp()
    count = 0
    for i in 0...s.length
    if s[i] == "@" || s[i] == "." || s[i] == "_"
    count += 1
    elsif s[i] == "@" || s[i] == "."
    count += 1
    end
    end
    if count == 3 || count == 2 && s.length>1
    puts "Valid Email"
    else
    puts "Not Valid Email"
    end

    ReplyDelete
  121. # Convert lower case to upper case
    puts "Enter the string: "
    str = gets.chomp()
    puts "select option! a) convert to lower case b) convert to upper case"
    con = gets.chomp()

    if con == "a"
    for i in 0...str.length
    if str[i] != str.length
    ch = str[i].to_s
    if ch >= "A" && ch <= "Z"
    str[i] = (ch.ord+32).chr
    else
    str[i] = ch
    end
    end
    end
    puts str
    end
    if con == "b"
    for i in 0...str.length
    if str[i] != str.length
    k = str[i].to_s
    if k >= "a" && k <= "z"
    str[i] = (k.ord-32).chr
    else
    str[i] = k
    end
    end
    end
    puts str
    end

    ReplyDelete
  122. s = "reshu"
    s1 = ""
    for i in 0...s.length
    s1 += (s[i].ord-32).chr
    end
    puts s1

    ReplyDelete
  123. # Program to convert String in Opposite case?
    print "Enter string upper/lower: "
    s = gets.chomp()
    s1 = ""
    for i in (s.length-1).downto(0)
    if s[i].ord >= 65 && s[i].ord <= 91
    s1 += (s[i].ord+32).chr
    else
    s1 += (s[i].ord-32).chr
    end
    end
    puts s1

    ReplyDelete
  124. # Program to convert String in Opposite case?

    print "Enter string: "
    s = gets.chomp()
    for i in (s.length-1).downto(0)
    print s[i]
    end
    puts

    ReplyDelete
  125. puts "Enter the string: "
    str = gets.chomp()
    puts "select option! a) convert to lower case b) convert to upper case"
    con = gets.chomp()

    if con == "a"
    for i in 0...str.length
    if str[i] != str.length
    ch = str[i].to_s
    if ch >= "A" && ch <= "Z"
    str[i] = (ch.ord+32).chr
    else
    str[i] = ch
    end
    end
    end
    puts str
    else
    for i in 0...str.length
    if str[i] != str.length
    k = str[i].to_s
    if k >= "a" && k <= "z"
    str[i] = (k.ord-32).chr
    else
    str[i] = k
    end
    end
    end
    puts str
    end

    ReplyDelete
  126. # password program

    print "Enter password: "
    pass = gets.chomp()
    count = 0
    for i in 0...pass.length
    if pass[i] == "@" || pass[i] == "." || pass[i] == "_"
    count += 1
    elsif pass[i] == "@" || pass[i] == "."
    count += 1
    end
    end
    if count == 3 && pass.length>8
    puts "Strong"
    elsif count == 2 && pass.length>8
    puts "Medium"
    else
    puts "Week"
    end

    ReplyDelete
  127. # 2) WAP to reverse String?

    str = "gnihtemos"
    reverse = ""
    str.length.times do |i|
    reverse.insert(i, str[-1-i].chr)
    end
    puts reverse

    ReplyDelete
  128. # 2 ay reverse
    str = "gnihtemos"
    j = str.length-1
    for i in 0..str.length/2
    k = str[i]
    str[i] = str[j]
    str[j] = k
    j -= 1
    end
    puts str

    ReplyDelete
  129. # check palindromic
    print "Enter string: "
    str = gets.chomp()
    s = (str.length)/2
    rev = -1
    for i in 0...s
    if str[i] == str[rev]
    rev -= 1
    puts "polindrome"
    break
    else
    puts "not polindrome"
    break
    end
    end

    ReplyDelete
  130. # 4) Count total numeric char in String?

    s ="reshu 543678 singh 3456"
    count = 0
    for i in 0...s.length
    # if s[i] == '0'|| s[i] == '1' || s[i] == '2' || s[i] == '3' || s[i] == '4' || s[i] == '5' || s[i] == '6' || s[i] == '7' || s[i] == '8' || s[i] == '9'
    if s[i] >= "0" && s[i] <= "9"
    print s[i]
    count += 1
    end
    end
    puts
    puts count

    ReplyDelete
  131. # table print using recursion
    puts "Table print"
    $a = 1
    def sum(num)
    if $a > 10
    return $a
    else
    b = $a * num
    puts "#{num.to_s}" "*" "#{($a).to_s}" "=" "#{b}"
    $a += 1
    return sum(2)
    end
    end
    sum(2)

    ReplyDelete
  132. puts "Fibonancci program"
    $a = 0
    $b = 1
    def func(num)
    if num > 5
    return num
    else
    sum = $a + $b
    print sum, " "
    $a = $b
    $b = sum
    return func(num+1)
    end
    end
    func(1)
    puts

    ReplyDelete
  133. # fibonancci series in recursion
    puts "Fibonancci program without using global variable"
    def func(a, b, num)
    if num < 0
    return num
    else
    sum = a + b
    print sum, " "
    a = b
    b = sum
    return func(a, b, num-1)
    end
    end
    a = 0
    b = 1
    func(a, b, 5)
    puts

    ReplyDelete
  134. # addition using recursion
    puts "Sum of number"
    $a = 0
    def sum(num)
    if num > 5
    return $a
    else
    $a += num
    puts "#{num.to_s}" "+" "#{($a-num).to_s}" "=" "#{$a}"
    return sum(num + 1)
    end
    end
    sum(1)

    ReplyDelete
  135. # # calculate factorial using recursion
    puts "Calculate factorial"
    $a = 1
    def fact(num)
    if num == 1
    return $a
    else
    $a *= num
    return fact(num - 1)
    end
    end
    fact(5)
    puts "Factorial of 5 is #{$a}."

    ReplyDelete
  136. # 6) WAP to find total prepositions in a paragraph
    # using predefine method
    s = "Your book is on the table. She was behind you"
    arr = s.split(" ")
    c = 0
    for i in 0...s.length
    if arr[i] == "on" || arr[i] == "behind"
    c += 1
    end
    end
    if c == 2 && arr.length>2
    puts "Total preposition #{c}"
    else
    puts "not"
    end

    ReplyDelete
  137. # not using predefine method
    s = "Your", "book", "is", "on", 'the', 'table.', 'She', 'was', 'behind', "you"
    c = 0
    for i in 0...s.length
    if s[i] == "on" || s[i] == "behind"
    c += 1
    end
    end
    if c == 2 && s.length>2
    puts "Total preposition #{c}"
    else
    puts "not"
    end

    ReplyDelete
  138. # fibonancci series in recursion
    puts "Fibonancci program"
    $a = 0-1
    $b = 1-0
    def func(num)
    if num > 5
    return num
    else
    sum = $a + $b
    print sum, " "
    $a = $b
    $b = sum
    return func(num+1)
    end
    end
    func(1)

    ReplyDelete
  139. # simple way sum of even and odd number using recursion

    $b = 5
    $c = 0
    $d = 0
    def func(a)
    if a <= $b
    if a%2 == 0
    $c += a
    else
    $d += a
    end
    else
    puts $c
    puts $d
    return 0
    end
    return func(a+1)
    end
    a = 1
    func(a)

    ReplyDelete
  140. # sum of even and odd number using recursion
    $count1 = 1
    $count2 = 1
    def func(a,b,c,d)

    if a <= b
    if a%2 == 0
    puts "Even number #{$count1}: #{a}"
    puts "add #{c}" + "+" + "#{a}" + "=" + "#{c+a}"
    c += a
    $count1 += 1
    else
    puts "Odd number #{$count2}: #{a}"
    puts "add #{d}" + "+" + "#{a}" + "=" + "#{d+a}"
    d += a
    $count2 += 1
    end
    else
    puts "Sum of total even number: #{c}"
    puts "Sum of total odd number: #{d}"
    return 0
    end
    return func(a+1,b,c,d)
    end
    a = 1
    b = 6
    c = 0
    d = 0
    func(a,b,c,d)

    ReplyDelete
  141. # sum of even and odd number using recursion

    class EvenOdd
    $count1 = 0
    $count2 = 0
    def func(a,b,c,d)
    if a <= b
    if a%2 == 0
    puts "Even number #{$count1+1}: #{a}"
    puts "add #{c}" + "+" + "#{a}" + "=" + "#{c+a}"
    c += a
    $count1 += 1
    else
    puts "Odd number #{$count2+1}: #{a}"
    puts "add #{d}" + "+" + "#{a}" + "=" + "#{d+a}"
    d += a
    $count2 += 1
    end
    else
    puts "Total even #{$count1} sum even number: #{c}"
    puts "Total odd #{$count2} sum odd number: #{d}"
    return 0
    end
    return func(a+1,b,c,d)
    end
    end
    print "Enter start number: "
    a = gets.to_i
    print "Enter ending number: "
    b = gets.to_i
    c = 0
    d = 0
    object = EvenOdd.new
    object.func(a,b,c,d)

    ReplyDelete
  142. # simple interest calculate using class method
    class SI

    def user_input()
    print "Enter principal: "
    @p = gets.to_i
    print "Enter rate: "
    @r = gets.to_i
    print "Enter time: "
    @t = gets.to_i
    end

    def variable_declare(p,r,t)
    @p = p
    @r = r
    @t = t
    end

    def logic()
    @SI = (@p*@r*@t)/100
    end

    def output()
    puts "Calculate SI: #@SI"
    end
    end
    obj = SI.new
    obj.variable_declare(@p,@r,@t)
    obj.user_input()
    obj.logic()
    obj.output()

    ReplyDelete
  143. # self onject use
    class SI
    def self.variable_declare(p,r,t)
    @p = p
    @r = r
    @t = t
    end

    def self.logic()
    @SI = (@p*@r*@t)/100
    end

    def self.output()
    puts "Calculate SI: #@SI"
    end
    end
    print "Enter principal: "
    p = gets.to_i
    print "Enter rate: "
    r = gets.to_i
    print "Enter time: "
    t = gets.to_i

    SI.variable_declare(p,r,t)
    SI.logic()
    SI.output()

    ReplyDelete
  144. # squre cube calculate using class and object
    class Squre_cube
    def define_var(s)
    @s = s
    end
    def cal_sq()
    @a = @s*@s
    @b = @s*@s*@s
    end
    def output()
    puts "#@s calculate squre: #@a"
    puts "#@s calculate cube: #@b"
    end
    end
    obj = Squre_cube.new
    obj.define_var(2)
    obj.cal_sq()
    obj.output()

    ReplyDelete
  145. # range based squre cube calculate using class and object
    class Squre_cube
    def define_var(start)
    @s = start
    end
    def cal_sq()
    @a = @s*@s
    @b = @s*@s*@s
    end
    def output()
    print "Calculate squre: #@a"
    print "\t Calculate cube: #@b"
    puts
    end
    end
    print "Enter any number: "
    start = gets.to_i
    print "Enter last number: "
    ending = gets.to_i

    obj = Squre_cube.new
    while start <= ending
    obj.define_var(start)
    obj.cal_sq()
    obj.output()
    start += 1
    end

    ReplyDelete
  146. # even and odd number using class method
    class EvenOdd
    def self.variable_declare(num)
    @a = num
    end

    def self.logic()
    @count = @a
    end

    def self.even_num()
    puts "Even number: #@count"
    end

    def self.odd_num()
    puts "odd number: #@count"
    end

    def self.sum_even()
    puts "sum of total even number: #@a"
    end

    def self.sum_odd()
    puts "sum of total odd number: #@a"
    end
    end

    print "Enter start number: "
    snum = gets.to_i
    print "Enter ending number: "
    lnum = gets.to_i

    for i in snum..lnum
    EvenOdd.variable_declare(i)
    EvenOdd.logic()
    if i%2 == 0
    EvenOdd.even_num
    else
    EvenOdd.odd_num
    end
    i += 1
    end

    ReplyDelete
  147. # sum of even and odd number and count even or odd
    class EvenOdd

    def self.even_num(snum)
    @a = snum
    puts "Even number: #@a"
    end

    def self.odd_num(snum)
    @b = snum
    puts "odd number: #@b"
    end

    def self.sum_even(count1,c)
    puts "Total count #{count1} even number and sum of even no: #{c}"
    end

    def self.sum_odd(count2,d)
    puts "Total count #{count2} odd number and sum of odd no: #{d}"
    end

    end

    print "Enter start number: "
    snum = gets.to_i
    print "Enter ending number: "
    lnum = gets.to_i

    count1 = 0
    count2 = 0
    c = 0
    d = 0
    for i in snum..lnum
    if i%2 == 0
    EvenOdd.even_num(i)
    count1 += 1
    c += i
    else
    EvenOdd.odd_num(i)
    count2 += 1
    d += i
    end
    i += 1
    end
    EvenOdd.sum_even(count1,c)
    EvenOdd.sum_odd(count2,d)

    ReplyDelete
  148. # 2 way sum of even and odd number and count even or odd
    class EvenOdd
    def self.variable_declare(snum)
    @a = snum
    end

    def self.even_num()
    puts "Even number: #@a"
    end

    def self.odd_num()
    puts "odd number: #@a"
    end

    def self.sum_even(count1,c)
    puts "Total count #{count1} even number and sum of even no: #{c}"
    end

    def self.sum_odd(count2,d)
    puts "Total count #{count2} odd number and sum of odd no: #{d}"
    end

    end

    print "Enter start number: "
    snum = gets.to_i
    print "Enter ending number: "
    lnum = gets.to_i

    count1 = 0
    count2 = 0
    c = 0
    d = 0
    for i in snum..lnum
    EvenOdd.variable_declare(i)
    if i%2 == 0
    EvenOdd.even_num()
    count1 += 1
    c += i
    else
    EvenOdd.odd_num()
    count2 += 1
    d += i
    end
    i += 1
    end
    EvenOdd.sum_even(count1,c)
    EvenOdd.sum_odd(count2,d)

    ReplyDelete
  149. * *
    ** **
    *** ***
    **** ****
    **********

    for i in 1..5
    for j in 1..i
    print "*"
    end
    for k in 1..5*2-i*2
    print " "
    end
    for l in 1..i
    print "*"
    end
    puts()
    end

    ReplyDelete
  150. * * *
    ** ** **
    *** *** ***
    **** **** ****
    ***************


    for i in 1..5
    for j in 1..i
    print "*"
    end
    for k in 1..5*2-i*2
    print " "
    end
    for l in 1..i
    print "*"
    end
    for m in 1..5*2-i*2
    print " "
    end
    for n in 1..i
    print "*"
    end
    puts()

    end

    ReplyDelete
Post a Comment