- Join elements of an
Array
withjoin
to produce aString
- Create an
Array
of words with Ruby's%w[]
literal - Split a
String
into anArray
of words
At this point in our journey, we're probably really keen to get some more data than just plain old numbers. It's a good time to cover to methods that are inverses of each other:
String
'ssplit
Array
'sjoin
Since we're in a module about Array
s, let's talk about joining an Array
of
words.
["This", "is", "a", "test"].join(' ') #=> "This is a test"
["This", "is", "a", "test"].join('_') #=> "This_is_a_test"
["This", "is", "a", "test"].join('*') #=> "This*is*a*test"
For more details, consult the join documentation.
Creating an Array
of words can be difficult to type with all those "
characters rolling about. Ruby invented an operator called the Array of Words
literal.
%w[this is also a test] #=> ["this", "is", "also", "a", "test"]
# For method-chaining fun:
%w[this is also a test].join(" ").capitalize #=> "This is also a test"
If Array's
join
can turn an Array
of Strings
into one String
, we can
reverse the process with String
's split
method:
"When in the course of human events".split(" ") #=> ["When", "in", "the", "course", "of", "human", "events"]
Here is a bit of Thomas Jefferson's Declaration of Independence.
These methods and the Array
word literal are tools to help you accomplish
programming tasks when working with text. There's a lot more to learn, but
these are a good start.