Pickaxe Book Chapter 02

Here are some notes on Chapter 2 of the Pickaxe book.


Single quoted strings take less processing, no interpolation
Return value of a method is the last statement, so you may not always want/need to put a “return” statement in there.
Local variables, method parameters and method names all start with lower case or underscore.
Global variables start with a dollar sign.
Instance variables start with an at symbol.
Class variables start with two at symbols.
Class names, module names and constants start with uppercase letter.
Character after @ may not be a digit
Multi-word instance variables get underscores between words, multiword class names get camel case.
Method names may end with ?, ! and =, although these have special meaning.

Arrays: like lists or arrays in Java, unlike primitive arrays you do not need to specify the size ahead of time.
Hashes: Like maps in Java.
The values do not need to be of the same type.
Shortcut for arrays:
a = [‘ant’, ‘bee’, ‘cat’, ‘dog’, ‘elk’]
same as
a = %w{ant bee cat dog elk}

Symbols: A lot of people in class had trouble with this concept. I am not too clear on it myself. They can be used as keys for hashes.
There is also a new Ruby 1.9 syntax for hashes.
Here is the old way:

inst_section = {
  :cello     = 'string',
  :clarinet  = 'woodwind',
  :violin    = 'string'

Now you can do this as well:

inst_section = {
  cello:    'string',
  clarinet: 'woodwind',
  violin:   'string'

This has caused some controversy on some Ruby mailing lists.
There are no braces for control structures. Instead Ruby uses the keyword “end”.
Next the book covers regular expressions. I am not going to get into details here. I have seen this before, although I know there is a lot to see.
Blocks are a bit weird to me. I will have to look them up somewhere. It seems to me like it is just another arg to a method. Is it special because it is code?
I altered some of the code from the book to make a method take a parameter as well as a block:

def call_block(arg)
  puts "Start of method"
  puts "arg is #{arg}"
  puts "End of method"

call_block('hello'){ puts "In the block" }
puts "About to call call_block with no block"
call_block('empty block'){}

The book says that blocks are used to implement iterators. I can never remember how to iterate through stuff. I will have to make a separate post about that.

cities = ['Chicago', 'Austin', 'Dallas' , 'Houston']
cities.each {|city| puts "The city is #{city}"}

3.upto()6 {|i| print i}
('a'..'e').each {|char| puts char}

The I/O section talks about printf. I thought the whole point of Ruby was not to deal with C?
puts prints to the terminal, gets gets from the terminal.
The command like arguments are in an array called ARGV.

Image from Wikimedia, assumed allowed under Fair Use. Image from the Vatican Virgil, a 5th century manuscript of poems by Virgil.