Chapter 2

  1. Here’s an implementation that uses our version of Array#each:

     class​ Array
     def​ each
      x = 0
     while​ x < self.length
     yield​ self[x]
      x += 1
     end
     end
     
     def​ map
      res = []
      each { |x| res << ​yield​(x) }
      res
     end
     end

    Here, we make use of the element that is yielded from each iteration of each and collect each element into res.

  2. Here’s a possible implementation:

     class​ String
     def​ each_word
      x = 0 ​# => 0
      words = self.split
     while​ x < words.length
     yield​ words[x]
      x += 1
     end
     end
     end
  3. Your final code should look something like this:

     class​ File
     def​ self.open(name, mode, &block)
      file = ​new​(name, mode)
     return​ file ​unless​ block_given?
     yield​(file)
     ensure ...

Get Mastering Ruby Closures 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.