Saturday, August 4, 2007

On ruby being a genuine OO language - no static method library thingies.. eg.
-1942.abs instead of Math.abs(-1942)
Ruby notes
  • String interpolation - "#{name.capitalize}"
  • Global variable - $greeting
  • Instance variable - @name
  • Class variables - @@count
  • Arrays use integers as keys, hashes can have any object as key
  • convenient word array instantiation: a = %w{ ant bee cat dog elk }
  • nil also means false
  • you can specify the default empty return value of a hash, eg. instead of return nil when lookup fails, you can return 0 - myhash = Hash.new(0)

  • Statement modifiers - convenient alternative ways of writing if and while statements if the body is just one line:
puts "Danger, Will Robinson" if radiation > 3000
square = square*square while square <>
  • Regular expressions are also objects. they are built into the language
  • matching: if line =~ /Perl|Python/
  • line.sub(/Perl/, 'Ruby') or line.gsub(/Perl/, 'Ruby')
Blocks
  • one line use braces, multi-line use do, end
  • pass them to methods, after all parameters
  • method can run the block any number of times using the yield method
  • Some people like to think of the association of a block with a method as a kind of parameter passing. This works on one level, but it isn’t really the whole story. You may be better off thinking of the block and the method as coroutines, which transfer control back and forth between themselves.
  • You can provide parameters to the call to yield: these will be passed to the block.
    Within the block, you list the names of the arguments to receive these parameters
    between vertical bars (|).
  • example uses of iterators:

[ 'cat', 'dog', 'horse' ].each {|name| print name, " " }
5.times { print "*" }
3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }



Classes and Objects
  • initialize method is the constructor - what gets called when you do Song.new
  • subclassing

class KaraokeSong < lyrics =" lyrics">

  • when subclassing, ruby doesn't know which object will provide the implementation of a method until runtime - it looks for an implementation of a method in the inheritance chain starting with the child.
  • shortcut for creating getters for instance variables :

class Song
attr_reader :name, :artist, :duration
end


Create setters using equals sign after method name
eg

def duration=(new_duration)
@duration = new_duration
end

then call it like this: song.duration = 33

1 comment:

strongcoffee said...

Virtual attributes - just "calculated" attributes - shielding the instance variables