
Spread Operator in Ruby and Ruby Ranges
Spread Operator in Ruby
Everyone remembers how revolutionary the introduction of the so-called spread operator
was in the JavaScript world with the ES6 standard. Working with collections became simple and pleasant. Combining arrays became trivial. One might think this makes JS unique in this regard... but no. We were using the spread operator in Ruby before it became trendy. So, if you want to learn what the spread operator in Ruby looks like and about Ruby Ranges (a very interesting object), I invite you to read on.
From my experience, Ruby is a language with a widely developed API when it comes to operations performed on collections. All thanks to the Enumerable
module and the Array
class, which provide all the interesting functionalities.
Concat
Indeed, Ruby has the concat
method, which is used to combine arrays with each other - the same action that is very frequently used in JS.
Ruby Magic
Let me show you an example of what a great language Ruby is. I'll use several less obvious array methods and another cool tool: Ruby Ranges.
Fake Password Generator
Let's write a simple password generator that we can use for database seeding, test data mocking, or generating temporary passwords for users.
Business Requirements:
Let's go!
The password can contain lowercase letters
No need to install anything, we'll use the Range
object, which allows us to generate a set of characters or numbers from a specific range. Then we'll convert this object to an array using the to_a
method.
The password can contain uppercase letters
We'll also use Range
here. We just need to change the parameters to uppercase characters.
The password can contain digits
And again, we'll use Range
.
*The password can contain special characters: $, #, ***
Here, a simple array will suffice.
Let's use a more fancy syntax to avoid typos and forgetting apostrophes.
The password can contain a randomly generated word in the Wookie language
This looks like the most difficult part, doesn't it?
I'll use the split
method, which accepts a space as the default separator and breaks down the generated sentence into an array of words understandable to Chewbacca.
Generating the Password
Now that we have all the components, it's time to generate the password. Let's first combine all the criteria into a single array.
Shuffle
Let's mix it up with the bang method.
Sample
Let's select 20 random elements and shuffle them again.
Join
Now we combine them and have a ready password.
Spread Operator
The complete code, with a small refactor simplifying the steps, looks like this:
Spread Operator
The complete code, with a small refactor simplifying the steps, looks like this:
Indeed, that's quite a bit of code, and I promised you the spread operator. Well, to combine arrays into one, all you need is the * symbol.
Final Code
The final code looks like this:
And it works like gold!