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

Week-07

Aprendizagem

  1. Symbols são literais String que são magicamente transformados em constantes.
    A Symbol is the most basic Ruby object you can create. It's just a name and an internal ID. Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.
  2. Um Symbol pode ser transformado num String e vice-versa, através dos métodos to_s() e to_sym().
  3. Uma classe pode ter até 3 níveis de protecção:
    • Public - os métodos podem ser evocados por qualquer entidade. Por omissão, os métodos de instância são públicos.
    • Protected - os métodos podem ser evocados por entidades da mesma família de classes: base e derivadas.
    • Private - os métodos apenas pode ser evocados no contexto da entidade que os define. O método initialize() é sempre private.
  4. É possível indicar no statement de protection level da classes quais os métodos que devem ter esse nível.
  5. O controlo de acesso é determinado dinamicamente, na altura da execução do programa, e não estaticamente. Ou seja, será devolvida uma access violation somente quando o código tentar executar um método para o qual não tenha permissão.
  6. Para facilitar a codificação de getters/setters basta atribuir um dos métodos Accessor à propriedade:
    • attr_reader() - apenas de leitura;
    • attr_writer() - apenas de escrita;
    • attr_accessor() - de leitura e/ou de escrita.
  7. Métodos top-level são métodos de instância de protecção private do módulo Kernel.
You can think of :id as meaning the name of the variable id, and plain id as meaning the value of the variable.

Ruby uses symbols, and maintains a Symbol Table to hold them. Symbols are names - names of instance variables, names of methods, names of classes. So if there is a method called control_movie, there is automatically a symbol :control_movie. Ruby's interpreted, so it keeps its Symbol Table handy at all times. You can find out what's on it at any given moment by calling Symbol.all_symbols.

Are instance variables inherited by a sub-class?
David Black, the author of Ruby for Rails, has this to say: Instance variables are per-object, not per-class, and they're not inherited. But if a method uses one, and that method is available to subclasses, then it will still use the variable – but “the variable” in the sense of one per object.

Exercícios

Exercício 1

exercise-01.rb

=begin
Write a class called Person,
that has balance as an instance variable
and the following public method: show_bal.
 
I shall create the Person object as follows:
 
p = Person.new(40000)
puts p.show_bal # calling the method
 
In the above code, 40000 is an amount figure that needs to be added to balance.
=end
 
class Person
 
  def initialize(amount)
    @balance = amount
  end
 
  def show_bal
    @balance
  end
 
end
 
p = Person.new(40000)
puts p.show_bal # calling the method

Exercício 2

exercise-02.rb

=begin
Write a Ruby program that analyzes a .mp3 file.
Many MP3 files have a 128-byte data structure at the end called an ID3 tag.
These 128 bytes are literally packed with information about the song:
its name, the artist, which album it’s from, and so on.
 
You can parse this data structure by opening an MP3 file and
doing a series of reads from a pos near the end of the file.
According to the ID3 standard,
if you start from the 128th-to-last byte of an MP3 file and read three bytes,
you should get the string “TAG”.
If you don’t, there’s no ID3 tag for this MP3 file, and nothing to do.
If there is an ID3 tag present, then the 30 bytes after “TAG” contain the name of the song,
the 30 bytes after that contain the name of the artist, and so on.
A sample song.mp3 file is available to test your program.
 
Use Symbols, wherever possible.
=end
 
GENRES = [                   \
    'Blues'                  \
  , 'Classic Rock'           \
  , 'Country'                \
  , 'Dance'                  \
  , 'Disco'                  \
  , 'Funk'                   \
  , 'Grunge'                 \
  , 'Hip-Hop'                \
  , 'Jazz'                   \
  , 'Metal'                  \
  , 'New Age'                \
  , 'Oldies'                 \
  , 'Other'                  \
  , 'Pop'                    \
  , 'R&B'                    \
  , 'Rap'                    \
  , 'Reggae'                 \
  , 'Rock'                   \
  , 'Techno'                 \
  , 'Industrial'             \
  , 'Alternative'            \
  , 'Ska'                    \
  , 'Death Metal'            \
  , 'Pranks'                 \
  , 'Soundtrack'             \
  , 'Euro-Techno'            \
  , 'Ambient'                \
  , 'Trip-Hop'               \
  , 'Vocal'                  \
  , 'Jazz+Funk'              \
  , 'Fusion'                 \
  , 'Trance'                 \
  , 'Classical'              \
  , 'Instrumental'           \
  , 'Acid'                   \
  , 'House'                  \
  , 'Game'                   \
  , 'Sound Clip'             \
  , 'Gospel'                 \
  , 'Noise'                  \
  , 'Alternative Rock'       \
  , 'Bass'                   \
  , 'Soul'                   \
  , 'Punk'                   \
  , 'Space'                  \
  , 'Meditative'             \
  , 'Instrumental Pop'       \
  , 'Instrumental Rock'      \
  , 'Ethnic'                 \
  , 'Gothic'                 \
  , 'Darkwave'               \
  , 'Techno-Industrial'      \
  , 'Electronic'             \
  , 'Pop-Folk'               \
  , 'Eurodance'              \
  , 'Dream'                  \
  , 'Southern Rock'          \
  , 'Comedy'                 \
  , 'Cult'                   \
  , 'Gangsta'                \
  , 'Top 40'                 \
  , 'Christian Rap'          \
  , 'Pop/Funk'               \
  , 'Jungle'                 \
  , 'Native US'              \
  , 'Cabaret'                \
  , 'New Wave'               \
  , 'Psychadelic'            \
  , 'Rave'                   \
  , 'Showtunes'              \
  , 'Trailer'                \
  , 'Lo-Fi'                  \
  , 'Tribal'                 \
  , 'Acid Punk'              \
  , 'Acid Jazz'              \
  , 'Polka'                  \
  , 'Retro'                  \
  , 'Musical'                \
  , 'Rock & Roll'            \
  , 'Hard Rock'              \
  , 'Folk'                   \
  , 'Folk-Rock'              \
  , 'National Folk'          \
  , 'Swing'                  \
  , 'Fast Fusion'            \
  , 'Bebob'                  \
  , 'Latin'                  \
  , 'Revival'                \
  , 'Celtic'                 \
  , 'Bluegrass'              \
  , 'Avantgarde'             \
  , 'Gothic Rock'            \
  , 'Progressive Rock'       \
  , 'Psychedelic Rock'       \
  , 'Symphonic Rock'         \
  , 'Slow Rock'              \
  , 'Big Band'               \
  , 'Chorus'                 \
  , 'Easy Listening'         \
  , 'Acoustic'               \
  , 'Humour'                 \
  , 'Speech'                 \
  , 'Chanson'                \
  , 'Opera'                  \
  , 'Chamber Music'          \
  , 'Sonata'                 \
  , 'Symphony'               \
  , 'Booty Bass'             \
  , 'Primus'                 \
  , 'Porn Groove'            \
  , 'Satire'                 \
  , 'Slow Jam'               \
  , 'Club'                   \
  , 'Tango'                  \
  , 'Samba'                  \
  , 'Folklore'               \
  , 'Ballad'                 \
  , 'Power Ballad'           \
  , 'Rhytmic Soul'           \
  , 'Freestyle'              \
  , 'Duet'                   \
  , 'Punk Rock'              \
  , 'Drum Solo'              \
  , 'Acapella'               \
  , 'Euro-House'             \
  , 'Dance Hall'             \
  , 'Goa'                    \
  , 'Drum & Bass'            \
  , 'Club-House'             \
  , 'Hardcore'               \
  , 'Terror'                 \
  , 'Indie'                  \
  , 'BritPop'                \
  , 'Negerpunk'              \
  , 'Polsk Punk'             \
  , 'Beat'                   \
  , 'Christian Gangsta Rap'  \
  , 'Heavy Metal'            \
  , 'Black Metal'            \
  , 'Crossover'              \
  , 'Contemporary Christian' \
  , 'Christian Rock'         \
  , 'Merengue'               \
  , 'Salsa'                  \
  , 'Trash Metal'            \
  , 'Anime'                  \
  , 'Jpop'                   \
  , 'Synthpop'               \
]
 
class MP3Data < String
 
  attr_accessor :tag, :song_name, :artist_name, :album_name, :year, :comment, :genre
 
  def initialize(input)
    # http://www.id3.org/ID3v1
    # http://www.mpx.cz/mp3manager/tags.htm
    # http://id3lib-ruby.rubyforge.org/ - id3lib-ruby
    @tag         = input.slice(  0,  3)
    @song_name   = input.slice(  3, 30)
    @artist_name = input.slice( 33, 30)
    @album_name  = input.slice( 63, 30)
    @year        = input.slice( 93,  4)
    @comment     = input.slice( 97, 30)
    @genre       = input.slice(127,  1)
  end
 
  def parsable?
    @tag == :TAG.to_s
    @tag.to_sym == :TAG
  end
 
end
 
file_handler = File.new('song.mp3', 'r')
file_handler.seek(-128, IO::SEEK_END)
input = file_handler.read(128)
mp3_data = MP3Data.new(input)
output = ''
output << 'Song Name:   ' + mp3_data.song_name   + "\n"
output << 'Artist Name: ' + mp3_data.artist_name + "\n"
output << 'Album Name:  ' + mp3_data.album_name  + "\n"
output << 'Year:        ' + mp3_data.year        + "\n"
output << 'Comment:     ' + mp3_data.comment     + "\n"
output << 'Genre:       ' + GENRES[mp3_data.genre.to_i]
puts output unless !mp3_data.parsable?

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. Métodos Accessor à propriedade duma classe facilitam imenso a codificação de uma classe.

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-07.txt · Modificado em: 2008/09/25 10:08 por straider     Voltar ao topo