Sunday, January 17

Ruby 101 - Part 2

After my successful blog post on Ruby 101 - Part 1 with millions of page views and thousands of comments ( yaah brah..just 1 view that too mine.. ;) ), i bring to you the part 2.

Basically we will just talk about Methods and Classes in Ruby.

Methods
1) Methods that return values

def sqare(num)
   return num*num
end

number = 2
numbersq = square(number)
puts(numbersq)


def power(base, exp)
   product = 1
   while exp > 0
      product *= base
      exp -=1
end
return product
end

print(power(4,3)


2) Methods that do not return value
def prompt(message)
   print(message)
end

prompt("Hello world")


3) Methods that take variable number of arguments
a) Variable no. of arguments

def sum(*args)
   total = 0
   for i in args
      total +=i
  end
  return total
end

b) Default arguments

def growth(principal, years, rate=1.01)
   while years > 0
     principal *= rate
     years -=1
  end
  return principal
end


Class

class Name
  def initialize(first, middle, last)
     @first = first
     @middle = middle
     @last = last
  end
end

aName = Name.new("jane", "Elizabeth", "Brown")
print aName.inspect


class Name
  def initialize(first, middle, last)
     @first = first
     @middle = middle
     @last = last
  end
end

def first = (first_name)
   @first = first_name
end

attr_reader :first, :middle, :last
attr_writer :first, :middle, :last

def to_s
   print(@last + ", " + @first + " " + @middle)
end

aName = Name.new("Jane", "Elizabeth","Brown")
aName.first = "Joan"
aName.middle = "Barbara"
aName.last = "Smith"

Class Variables - Variable whose value can be accessed throughout the class
eg. @@count

class Person
   def initialize(name, age, gender)
      @name = name
      @age = age
      @gender = gender
   end

   def to_s
      print("Name : ", @name, "\n")
      print("Age : ", @age, "\n")
      print("Gender : ", @gender, "\n")
   end

  def birthday
     @age +=1
  end
end

Inheritance - Access instance variable and methods from superclass

Modules
Take code from one file and put in another program, use require.

Be the first one to Comment!!!

Post a Comment