Sunday, August 19, 2007

Attribute writers
attr_writer bla

There are numerous ways to define class methods.

Make methods public, protected and public by using the keyword then any methods that come after that keyword fall under accessor.

Protected methods are accessible from the objects of the defining class and its subclasses. Private methods can only be called by the object of class that defines them. Protected access can also occur between objects of the same class. Methods are public by default.

dup method

person1 = "Jim"
person2 = person1.dup
person1[0] = 'T'
person1 -> "Tim"
person2 -> "Jim"


Freeze an object from modification using the 'freeze' method

Creating arrays

a = [1.3, "foo", 55]
a = Array.new
a[0] = "bla"
a[1] = 4
a[5] -> nil


There are all sorts of ways you can manipulate arrays, similar to perl. There are also apparently lots of methods on arrays that lets you use them as queues, stacks eg push, pop

To support chaining, return "self" (have self as last line in method).

Iterators and blocks
@songs.find {|song| title == song.name }


Blocks
  • start on same line as method call after last parameter or parentheses
  • variables and scope is a little complicated - if you are passed local variables from the method, the block can alter these. it can have its own locally defined variables, or also inherit the variables from surrounding code.
collect iterator applies result of block back to its arguments
[1, 2].collect{ |d| d+=1 }  -> [2, 3] 


inject for accummulating along a list. (can leave the parameter off and it will use the first element)
 [1,2,3].inject(0) { |sum, element| sum+=element }


Args pointer

class File
def File.open_and_process(*args)
f = File.open(*args)
yield f
f.close()
end
end


If File.open has an associated block, then that block will be invoked with a file object, and the file will be closed when the block terminates.

Some kernel methods:
  • defined?
  • Kernel.block_given?
Using blocks as closures:

songlist = SongList.new
class JukeboxButton < action =" action" start_button =" JukeboxButton.new(">


That code block is converted to an object of class Proc and assigned to the parameter

Associated with a block (and hence a Proc object)
is all the context in which the block was defined: the value of self and the methods,
variables, and constants in scope. Part of the magic of Ruby is that the block can still
use all this original scope information even if the environment in which it was defined
would otherwise have disappeared. In other languages, this facility is called a closure.


def n_times(thing)
return lambda {|n| thing * n }
end

p1 = n_times(23)
p1.call(3) ! 69


The method n_times returns a Proc object that references the method’s parameter,
thing. Even though that parameter is out of scope by the time the block is called, the
parameter remains accessible to the block.

No comments: