Thursday, 17 November 2016

Ruby classes methods

Methods in Ruby:

Ruby methods are used to bundle one or more repeatable statements into single unit

Syntax:

    def methodname

        statement1
        statement 2
         ,,,,,,,,,,,,,,,,,

   end


Example:

def Systeminfo(a,b,c)
  puts "The ram size is #{a}"
  puts "The hard disk info  is  #{b}"
  puts "The OS type is #{c}"
end

Systeminfo("4GB","400GB","Centos")

Output:



Class

A class is blueprint for  making objects.When we use a class to make an object, the class describes what object knows about itself, as well as what object does.

Ruby Object

An object is an instance which has set  of  data and methods which operate on that data  in one place

Advantages of Class


  1. Puts data at single unit
  2. Reduces the complexity
  3. Makes programmer easier


Syntax:

 class Classname
   def mehtod1
     statement1
     statement2
     ,,,,,,,,,,,,,,,n
   end
   def metod2
     statement1
     statement2
     ,,,,,,,,,,,,,,,,n
   end
end


Example:

   class Account
     def ac_deposit(d)
       @balance=10000
        @balance=@balance+d
      end
      def withdraw(a)
        @balance=a
      end

     def show_bal
        puts "Current balance: #{@balance}"
     end
end

currentAC=Account.new
currentAC.ac_deposit(500)
currentAC.show_bal
currentAC.withdraw(2000)
currentAC.show_bal

 



     

No comments:

Post a Comment