1. Arrays, Hashes, and Enumerables

1. Arrays, Hashes, and Enumerables

Check the Ruby 2.x documentation on Array, Hash and Enumerable as they could help tremendously with these exercises. Various Ruby cheatsheets are also helpful as a quick reference! Although Ruby supports looping constructs like ‘for’ and ‘while’, consider using block syntax with each for a more idiomatic use of Ruby. :-)

  1. Define a method sum(array) that takes an array of integers as an argument and returns the sum of its elements. For an empty array it should return zero. Run associated tests via: $ rspec -e '#sum ' spec/part1_spec.rb (Make sure you are in the correct directory: cd assignment and rspec is installed).
  1. Define a method max_2_sum(array) which takes an array of integers as an argument and returns the sum of its two largest elements. For an empty array it should return zero. For an array with just one element, it should return that element (Consider if the two largest elements are the same value as well). Run associated tests via: $ rspec -e '#max_2_sum' spec/part1_spec.rb
  1. Define a method sum_to_n?(array, n) that takes an array of integers and an additional integer, n, as arguments and returns true if any two elements in the array of integers sum to n. sum_to_n?([], n) should return false for any value of n, by definition. Run associated tests via: $ rspec -e '#sum_to_n' spec/part1_spec.rb

You can check your progress on all of the above by running $ rspec spec/part1_spec.rb. Note that if all tests are failing (including the definition ones, e.g. “#sum should be defined”), you likely forgot to run bundle from the assignment directory as mentioned on the previous page.

rspec spec/part1_spec.rb

Submission (10 points)

You should now be ready to submit your assignment. Remember to run your test cases once more, then submit your files to Gradescope, Codio or whichever platform your course is using.


This site uses Just the Docs, a documentation theme for Jekyll.