Appendix A. Solutions

Chapter 1

  1. Exercise 1 is about learning to read a file and exploring the array methods using the contents of the file. I’d expect to see something like this in the console after completing the exercise:

    irb(main):001:0> file = File.read("test.txt")
     => "Call me Ishmael..."
    irb(main):002:0> puts file.split
    Call
    me
    Ishmael
    --snip--
     => nil
    irb(main):003:0> puts file.split.length
     => 198
    irb(main):004:0> puts file.split.uniq.length
     => 140

    The output depends on the text you used.

  2. The second exercise requires writing a little code. The following sample solves the problem using only methods covered so far:

    file = File.read("test.txt") counts = {} file.split.each do |word| if counts[word] counts[word] = counts[word] + 1 else counts[word] ...

Get Rails Crash Course now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.