Pickaxe Book Chapter 04

This chapter starts out with arrays (square brackets) and hashes (curly braces), which are important to know. It says that blocks when combined with collections are good iterators. The elements in arrays and hashes can be any type. Using different methods, arrays can be different data structures: sets, queues, dequeues, FIFO queues, instead of using different classes. In Ruby hashes, it keeps the objects in the order they were entered. Keep the names of the block parameters unique. You could use a colon, but I think it is better to keep them unique.

A block can be empty:

def three_times
    puts "in method three_times"
    puts "leaving three_times"

three_times { } 
# { puts "Hello" }

But you must put in a block if a method has “yield” in it, even if yield has a parameter

To keep track of how many times you have gone through the loop, instead of each, use each_with_index. You will need a second variable for the block: index to track the count.

f = File.open("para.txt")
f.each_with_index do |line,index|
    puts "Line #{index} is: #{line}"

I did not quite get the “inject” method, and I skipped over some of the stuff about enumerators since it said I could.
Class methods start with the word “self” in front of them

At the end it gets into using blocks for closures and lambdas. Do we get into that with Rails? I think I get this stuff, but sometimes I have to look at it for a few minutes to get it. I don’t think I really know too well. Plus it appears there is another syntax for Ruby 1.9, which makes it more confusing.

There is an encouraging note at the end that if you don’t get it now, it’s okay. Thanks, Dave!

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

There are 327 words in this article.