#6 Making a List (array_join.rb)

In the previous script, we added new methods to allow explicit Boolean casting to every Object in all of Ruby. In this example, we create a new method that is a slight variation on a method that already exists. In this case, we’re altering the way that Arrays can represent themselves as Strings.

When we talk about lists in natural speaking, we often separate the last item from the item before it with the word and. This is not how Ruby handles Arrays by default. Let’s verify that in irb:

irb(main):001:0> a = [0, 1, 2]
=> [0, 1, 2]
irb(main):002:0> a.join(' ')    The join Method
=> "0 1 2"
irb(main):003:0> a.join(', ')
=> "0, 1, 2"
irb(main):004:0> a.join('')
=> "012"

We’re creating a variant of the method join, which ...

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.