Manasi Salvi

Ruby Arrays

Working through Exercism has some great exercises to brush up on coding skills. This particular challenge involved converting a phrase to its acronym. The coding challenge is to make the failing tests pass by writing the corresponding code. The first test was as follows:

class AcronymTest < Minitest::Test
  def test_basic
    assert_equal "PNG", Acronym.abbreviate('Portable Network Graphics')
  end
end

Firstly the problem needed to be broken down so I began with some basic instructions to myself:

The code was as follows. The words following ‘//’ is the output in the irb (interactive ruby console).

class Acronym
  def self.abbreviate(phrase)
    array = phrase.split(' ') // ["Portable", "Network", "Graphics"] 
    array_2 = array.each_slice(1).to_a // [["Portable"], ["Network"], ["Graphics"]]
    array_3 = array_2[0][0][0] // "P"
    array_4 = array_2[1][0][0] // "N"
    array_5 = array_2[2][0][0] // "G"
    array_6 = [array_3, array_4, array_5].join // "PNG"
  end
end

Prior to this exercise I wasn’t aware of the each_slice method in Ruby which allows you to split an Array of Strings into an Array of sub-Arrays. It was a question in Stack Overflow that lead me to this discovery. There were also a few lessons in syntax such as for the ‘.join’ method which took a bit of playing around in irb to eventually realise simplicity was the answer. I initially also thought the final answer would require converting an array into a string to return the acronym however Ruby does this for you thus not requiring such a step. I am still working through the rest of this problem so I will be refactoring this solution into better naming patterns, shortening it where possible and including support for lower case characters, punctuations, all caps words etc. as part of the challenge - more to come as I work through the challenge.