O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required