Now I can reference the hash, add components of that hash to my accumulator and choose to return that accumulator or the original number being passed to the method based on the code inside the block just as described above. However, instead of working only with the key/value pairs of the hash, here I am working with a base argument of an empty string, an accumulator, or ‘acc’, which I can add to and return as my result, and a final argument of the hash (‘input’) of information I am comparing my number to. Similar to the ‘each’ method, I am working with multiple arguments in the ‘inject’ method. I created a hash with key/value pairs between the numbers listed in the instructions (3, 5, 7) and their associated string value… conversion = def nvert(num) conversion = do |acc, input| if num % input = 0 acc << input end acc end return num.to_s if conversion.empty? conversion end end If we pass in 34, we expect to get back "34", as none of our 3 factors listed above are factors of 34. If we pass in 30, we expect to get back "PlingPlang", as 3 and 5 are both factors of 30. For example: If we pass in 28, we expect to get back "Plong", as 7 is a factor of 28. If the number does not have 3, 5, or 7 as a factor, just pass the number's digits straight through. If the number has 7 as a factor, output 'Plong'. If the number has 5 as a factor, output 'Plang'. If the number has 3 as a factor, output 'Pling'. The challenge: convert a number to a string, the contents of which depend on the number’s factors. The following is a snap shot of one of my first code challenges, Raindrops, which I like to call “Pling”, “Plang”, “Plong”, where I begin the first solution using ‘each’ and through a couple of iterations, land at a solution using the ‘inject’ method. I know that, but which one to start with?Īfter meeting with a mentor about my dilemma, I decided, I would create a local repo of all the code challenges I had worked on adding new iterations to each of them with different ways of solving the problem. Should I use ‘each’, or ‘this’ or ‘that’…they could all work. It was messy not only in my text editor, but also in my head. While this was a good process, I found that as I was trying to solve the problem in my text editor I would have three different versions of not quite working code. I would look at the instructions, analyze the problem, write out some pseudocode solution and then dive in. When I first started, I felt pretty overwhelmed at all the possible ways to solve each challenge. Raindrops Code Challenge: an iterative process from ‘each’ to ‘inject’ w/ “Pling”, “Plang”, “Plong”Īs a Ruby on Rails software developer student, I learned the importance of practicing code challenges.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |