O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required