This is the last article in the Guide to Ruby Collections series. I want to finish up by providing some miscellaneous tips that you will hopefully find helpful during your Ruby adventures.

More Detailed Array Creation

In the introduction to Arrays, I showed you that you can fill an array with a default value by passing a second argument to Array.new

>> Array.new(3, 1)
=> [1,1,1]

So if we wanted to initialize an Array with random numbers, we could just pass in rand(x) instead, right?

>> Array.new(3, rand(100))
=> [28,28,28]

Hmm. That wasn’t exactly random. It looks like rand(100) is only being evaluated once. Fortunately, Array#new can take a block, and it will run the block for each element, assigning the element the result.

>> Array.new(3) { rand(100) }
=> [10,53,27]

Mass Assignment

Similar to Python, Ruby allows assignment to more than one variable, or more than one index in an Array, in the same statement.

!!WARNING!!: Monkeying around with Ruby’s core libraries could result in bugs that are very difficult to track down. In fact, even the previous example kills Array’s ability to accept more than one argument and appears to cause errors in irb. If you don’t want to research how to redefine Array methods without causing problems, a safer alternative would be to create a subclass of Array.

Random Array Elements

We’ve seen how to create random numbers in Ruby, but what about anything else? Perhaps your significant other has recently implemented a method like this:

>> def random_restaurant
>> "I don't care. Where do you want to go?"
>> end
>> 3.times.map { random_restaurant }
=> ["I don't care. Where do you want to go", "I don't care. Where do you want to go", "I don't care. Where do you want to go"]

Choking back tears of frustration, you could put a selection of nearby restaurants into an array and use the #sample method to get one at random.

The NArray gem is not limited to integers or NArray objects. The English documentation for NArray can be found here

Benchmarking

With the seemingly infinite number of ways to access and manipulate Ruby collections, you might be left wondering how to determine whether the methods you are using are efficient. For example, is it really faster to perform a membership test with Set than with Array?