วันพุธที่ 18 พฤศจิกายน พ.ศ. 2558

ลอง RUBY WHILE + Function + class + array (find_age & average_age)

class Student
  def initialize(name,id,age)
    @name, @id, @age = name, id, age
  end

  def get_name
    return @name
  end

  def get_age
    return @age
  end
 
end

def average_age(std)
i=0
sum = 0
avg = 0
while i<3
sum = sum+std[i].get_age
i = i+1
end
avg = sum/3
puts "The average age in this classroom = #{avg}"
end

def find_age(std, age)
  i=0
  count=0
  while i<3
    if std[i].get_age<=age
      count=count+1
      puts "#{std[i].get_name} is #{std[i].get_age} years old"
    end
i = i+1
  end
  puts "This classroom have #{count} students with age < 30"
end
 

def setup
  data_student = [Student.new("A",1,25),
          Student.new("B",2,34),
          Student.new("C",3,27)]

  find_age(data_student, 30)
  average_age(data_student)

end

setup

ไม่มีความคิดเห็น:

แสดงความคิดเห็น