Avatar of remcopeereboom

remcopeereboom's solution

to Accumulate in the Ruby Track

Published at Jul 13 2018 · 7 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Implement the accumulate operation, which, given a collection and an operation to perform on each element of the collection, returns a new collection containing the result of applying that operation to each element of the input collection.

Given the collection of numbers:

  • 1, 2, 3, 4, 5

And the operation:

  • square a number (x => x * x)

Your code should be able to produce the collection of squares:

  • 1, 4, 9, 16, 25

Check out the test suite to see the expected function signature.

Restrictions

Keep your hands off that collect/map/fmap/whatchamacallit functionality provided by your standard library! Solve this one yourself using other basic tools instead.

Advanced

It is typical to call #to_enum when defining methods for a generic Enumerable, in case no block is passed.

Here is an additional test you could add:

def test_accumulate_when_block_is_deferred
  skip
  accumulate_enumerator = [1, 2, 3].accumulate
  accumulated_result = accumulate_enumerator.each do |number|
    number * number
  end
  assert_equal [1, 4, 9], accumulated_result
end

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

gem install minitest

If you would like color output, you can require 'minitest/pride' in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

ruby accumulate_test.rb

To include color from the command line:

ruby -r minitest/pride accumulate_test.rb

Source

Conversation with James Edward Gray II https://twitter.com/jeg2

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

accumulate_test.rb

require 'minitest/autorun'
require_relative 'accumulate'

class ArrayTest < Minitest::Test
  def test_empty_accumulation
    assert_equal [], [].accumulate { |e| e * e }
  end

  def test_accumulate_squares
    skip
    result = [1, 2, 3].accumulate do |number|
      number * number
    end
    assert_equal [1, 4, 9], result
  end

  def test_accumulate_upcases
    skip
    result = %w(hello world).accumulate(&:upcase)
    assert_equal %w(HELLO WORLD), result
  end

  def test_accumulate_reversed_strings
    skip
    result = %w(the quick brown fox etc).accumulate(&:reverse)
    assert_equal %w(eht kciuq nworb xof cte), result
  end

  def test_accumulate_recursively
    skip
    result = %w(a b c).accumulate do |char|
      %w(1 2 3).accumulate do |digit|
        "#{char}#{digit}"
      end
    end
    assert_equal [%w(a1 a2 a3), %w(b1 b2 b3), %w(c1 c2 c3)], result
  end

  def test_do_not_change_in_place
    skip
    original = [1, 2, 3]
    copy = original.dup
    original.accumulate { |n| n * n }
    assert_equal copy, original
  end

  # Problems in exercism evolve over time, as we find better ways to ask
  # questions.
  # The version number refers to the version of the problem you solved,
  # not your solution.
  #
  # Define a constant named VERSION inside of the top level BookKeeping
  # module.
  #  In your file, it will look like this:
  #
  # module BookKeeping
  #   VERSION = 1 # Where the version number matches the one in the test.
  # end
  #
  # If you are curious, read more about constants on RubyDoc:
  # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html

  def test_bookkeeping
    skip
    assert_equal 1, BookKeeping::VERSION
  end
end
class Array
  def accumulate(&block)
    return enum_for(:accumulate) unless block_given?
    a = []

    for i in 0...length
      a[i] = yield self[i]
    end

    a
  end
end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of remcopeereboom

Little magic here. The enum_for method is perhaps redundant if you don't wan't to return an enumerator. I don't know if the for loop uses #each internally, but it seems the least magical thing you can do in ruby...

Avatar of monkbroc

Spread the word! enum_for is great for methods that yield to blocks and that might be chained with other Enumerable methods.

Great blog post about this topic http://blog.arkency.com/2014/01/ruby-to-enum-for-enumerator/

Avatar of remcopeereboom

Thanks! I've been looking for a nice blog post on enumerators. Most tend to be on enumerable and completely ignore enumerator.

Avatar of monkbroc

BTW, I ended up using the enum_for code in my main application today. A CSV importer passes an enumerator to a consumer for the data. Simple and low ceremony. importer.import(csv.each_record)

Avatar of remcopeereboom

@monkbroc :)

Enumerators are actually really great to pass along as parameters, but you don't really come across them in the wild. I wrote a little drawing module for a fluid dynamics code base a long while back. We wanted to draw some solids in a grid without needing to port the whole solution to a professional package. At first I considered writing it in native code which would have cost more time than just porting, but then I thought... hey this is just the setup. I can do that in ruby. I ended up having a few overloaded draw and other utility methods that all took an optional enumerator to fill in the cells (would default to each I think), so I could pass an each_in_cylinder or an each_in_sphere. and have it fill in those cells. It made everything so flexible, but would have been much more cumbersome to use without enum_for.

Avatar of pikislabis

Is it necessary the &block argument?

I have implemented the accumulate function without that parameter and it works.

Avatar of remcopeereboom

@pikislabis No, the &block argument is not necessary and these days I tend to leave it off. But I used to use it to indicate that the method is expected to work with a block. It was a kind of code documentation, but these days I just write proper documentation in Ruby just like I would in other languages. I still use the &block if I work with external Ruby code that does the same, however.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?