I’ve been working through the Ruby track on Exercism.io. I’ve found this to be an incredibly useful resource to practice writing cleaner code and for the mentoring aspect. The other helpful aspect of this resource is the community solutions. There’s a dozen ways to write a solution to a coding problem. Seeing how others approach the same problem was valuable and a great learning resource in itself.
Here are some of the Array manipulation methods I found the most useful and referring to most often when solving the ruby track problems.
-
The splat operator for passing “catch-all” arguments
Perfect for passing an array into a function expecting multiple arguments to a method. This blogpost was helpful: https://www.honeybadger.io/blog/ruby-splat-array-manipulation-destructuring/
-
.map and .each
Great for looping through arrays. Main difference being that .each returns the original array whereas the .map returns a new array modified with your code. https://www.freecodecamp.org/news/six-ruby-array-methods-you-need-to-know-5f81c1e268ce/
-
.join
I’ve found myself trying to google for turning the result of a method returning the contents of an array into a single string or multiple strings. This was the perfect way of achieving this. https://www.freecodecamp.org/news/six-ruby-array-methods-you-need-to-know-5f81c1e268ce/
-
.flatten
I’m referring to this in context of arrays, however it can be useful for hashes too.
Useful for flattening multiple nested arrays into one by recursively flattening it. https://apidock.com/ruby/Array/flatten
-
.take()
Takes enumerable and returns the first n element(s) from the array in a new array. If you pass .take(0) it returns #=> [].
-
.each_char
A string method - for passing each character in a string to a block.
-
.include?
A string method - returns true/false if a string contains a character or string.
-
.all?
Returns true if arguments arent false or nil. Just be careful with passing empty arrays as an argument - it returns true.
-
.scan
-
Regex (/\w/) vs. [[:alpha:]] or [a-zA-Z]
This is based on feedback from Exercism.io for an Acronym problem involving abbreviating the arguments. Using [[:alpha:]] or [a-zA-Z] is more useful in real world scenarios to explicitly exclude ‘_’ as a character.
Resources I found useful:
- http://www.korenlc.com/nested-arrays-hashes-loops-in-ruby/
- https://dev.to/molly_struve/level-up-your-ruby-skillz-working-with-arrays-hnn#chaining
- https://www.rubyguides.com/2015/06/ruby-regex/
- http://zetcode.com/lang/rubytutorial/regex/
- http://ruby-for-beginners.rubymonstas.org/advanced/regular_expressions.html
comments powered by