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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.