The Ruby Programming Language

Proc

class Student
  def initialize
    @data = {}   #empty hash
    @grades = [] #empty array
  end

  def addThreeGrades(a,b,c)
    @grades.push(a)
    @grades.push(b)
    @grades.push(c)
  end

  def addData(d)
     d.each do |key, value|
       @data[key] = value
     end
  end

  def eachGrade
    @grades.each do |g|
      yield(g)
    end
  end

end

s = Student.new()

g = [70,80,90]

#The * before the g blows up the array into arguments
s.addThreeGrades(*g)

# Adds all these to @data hash table
s.addData :name => "joe", :id => "12345", :year => 3

#Add another one
s.addData :major => "CSCE"

#Create a Proc object. prints x*2
timesTwo = lambda {|x| puts x * 2}

#To pass a Proc as a block it must be preceeded by &
# and be the last argument.
s.eachGrade(&timesTwo) #140 160 180, each on a new line

José M. Vidal .

9 of 11