:: Topo :: doCoding :: Linguagens de Programação :: Ruby :: FORPC101 ::

Week-08

Aprendizagem

  • Hashes são Arrays associativos, na medida em que em vez de se aceder a cada elemento com um índice inteiro se acede a cada valor através da sua “chave” - pair key, value - que pode ser de qualquer tipo, mesmo dentro do mesmo Hash.
  • O “zero” inicial para a classe Time é o primeiro segundo do dia 1 de Janeiro de 1970.
  • A classe DateTime é superior à classe Time para aplicações astronómicas e históricas.

Exercícios

Exercício 1

exercise-01.rb

=begin
Write a method called month_days, that determines the number of days in a month.
 
Usage:
days = month_days(5) # 31 (May)
days = month_days(2, 2000) # 29 (February 2000)
 
Remember, you would require the Date class here.
Read up the online documentation of the same.
=end
 
def is_leap_year?(year)
  check = case
    when year % 400 == 0 : true
    when year % 100 == 0 : false
    when year % 4   == 0 : true
  else
    false
  end
end
 
# Time.month_days(year, month)
def month_days(month, year = Time.now.year)
 
  days_in_month = {
      31 => [1, 3, 5, 7, 8, 10, 12] \
    , 30 => [4, 6, 9, 11]
  }
 
  days = nil
  if month == 2 then
    days = is_leap_year?(year) ? 29 : 28
  else
    # key has number of days and value has the array of months.
    days_in_month.each_pair do | key, value |
      days = key if value.include?(month)
    end
  end
  return days
end
Exercício resolvido sem recorrer à classe Date, que precisa de um require 'date', e que usa código de exercícios anteriores - neste caso para validar se é um não um ano bissexto.

Exercício 2

exercise-02.rb

=begin
Write a method last_modified(file) that
takes a file name and
displays something like this:
file was last modified 125.873605469919 days ago.
 
Use the Time class.
=end
 
def last_modified(filename)
  'File was last modified ' + time_diff_in_days(File.mtime(filename), Time.now).to_s + 'days ago.'
end
 
def time_diff_in_days(time_begin, time_end)
  (time_end - time_begin).to_f / 60 / 60 / 24
end
 
puts last_modified('exercise-02.rb')

Exercício 3

exercise-03.rb

=begin
Let's say you want to run some Ruby code (such as a call to a shell command),
repeatedly at a certain interval.
Write a method for this.
Do not use Thread class for now.
Hint: yield and sleep methods may be required.
=end
 
def block_poller(interval = 1, duration = 5, &block)
  stop_time = Time.now + duration
  while Time.now < stop_time
    yield
    sleep(interval)
  end
end
 
block_poller() { puts 'Time is now ' + Time.now.to_s }
block_poller(2, 10) { puts 'Will sleep for 2 seconds from now (' + Time.now.to_s  + ')' }

Questionário

Referências

Considerações

Pontos Altos

Esta secção regista o que considero serem os pontos altos da linguagem Ruby quando comparada com outras linguagens que conheço.

  1. A classe Hash é muito flexível.
  2. O uso de Symbols como chaves de um Hash é bastante apropriado.
  3. A classe Time é bastante flexível, tal como a funcionalidade similar em C - strftime.

Pontos Baixos

Esta secção regista o que considero serem os pontos baixos da linguagem Ruby quando comparada com outras linguagens que conheço.

 
docoding/languages/ruby/forpc101/week-08.txt · Modificado em: 2008/09/25 10:08 por straider     Voltar ao topo