Saturday, September 8, 2007

For both attr_reader and attr_writer, just use attr

Method naming conventions, ? for queries, ! for 'dangerous' methods eg. those that modify the receiver.

Specify defaults to method parameters: def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach")

Variable length argument lists: def varargs(arg1, *rest)

Store block passed in in parameter: def initialize(name, &block)

private methods cannot be called with a "receiver"

You can return multiple things and ruby will put them into an array. You can assign these with the multi-assign thingy:

return num, square if square > 1000
num, square = meth_three

You can "explode" arrays when passing them to a method. It maps elements of the array to the parameters.

Ruby imitates keyword arguments with hashes as last parameter.

You can run OS commands by specifying them in backquotes. eg. `date`. It captures stdout.

Assignment returns back the assigned value so you can do things like File.open(name = gets.chomp)

Parallel assignment a, b = b, a
Parallel assignments and expanding arrays,

a = [1, 2, 3, 4]
b, c = a ! b == 1, c == 2
b, *c = a ! b == 1, c == [2, 3, 4]

There is also nested parallel assignment, which is a bit psycho.


words[key] ||= [] -> words[key] = words[key] || []


Case statement - you can have multiple matchers

kind = case year
when 1850..1889 then "Blues"
when 1940..1950 then "Bebop"
else "Jazz"
end


You can use while and until as "statement modifiers"

a *= 2 while a < 100
a -=10 until a < 100

No comments: