DEV Community

Mbonu Blessing
Mbonu Blessing

Posted on

Two ways to convert a string to an array in Ruby

Hello everyone.
This week, I will be sharing 2 ways I have learnt how to convert a string to an array of characters. A little backstory, I was solving an algorithm on Codewars and it required me converting the string to an array. I solved it with the method I know and after submitting, I scrolled through other answers to learn how others did theirs and possible pick up one or two new knowledge.

The two methods are chars and split. They both return an array of characters but one is better than the other.

Using Chars

Let's use the string 'programming'

word = 'programming'
word.chars

# => ["p", "r", "o", "g", "r", "a", "m", "m", "i", "n", "g"]
Enter fullscreen mode Exit fullscreen mode

On a sentence, we showcase how to do this with the example below

sentence = 'Ruby is great'
sentence.chars

# => ["R", "u", "b", "y", " ", "i", "s", " ", "g", "r", "e", "a", "t"]

As you can see, it returns all the characters even the `space`
Enter fullscreen mode Exit fullscreen mode

Using Split

To use split, we need to pass a parameter that tells it how to split the string.

word = 'programming'
word.split('') # '' tells it to return each characters

# => ["p", "r", "o", "g", "r", "a", "m", "m", "i", "n", "g"]
Enter fullscreen mode Exit fullscreen mode

For a sentence, we might want to only return each words in it.

sentence = 'Ruby is great'
sentence.split(' ') # tells it to split anywhere there is a space

# => ["Ruby", "is", "great"]
Enter fullscreen mode Exit fullscreen mode

We can also split at a character.

'kolloioll'.split('o')
# => ["k", "ll", "i", "ll"]
Enter fullscreen mode Exit fullscreen mode

You can also pass regex to the split method

# split at every `fullstop` before a `comma`
"sha.,ger.,ffd.,uio.".split(/.(,)/)

# => => ["sha", ",", "ger", ",", "ffd", ",", "uio."]
Enter fullscreen mode Exit fullscreen mode

Difference between them

Given that split works on string using regex, it fails on strings that contains invalid characters.

"love\x80light".chars

#=> ["l", "o", "v", "e", "\x80", "l", "i", "g", "h", "t"]
Enter fullscreen mode Exit fullscreen mode
"love\x80light".split('')

#=> ArgumentError (invalid byte sequence in UTF-8)
Enter fullscreen mode Exit fullscreen mode

Another difference is that unlike split where you can specify where to split from, you can't do that for chars. You can only use it when you need to return all the characters in a string as an array

Resources

Stackoverflow answer to difference between char and split
API dock - String split

Let me know if you have an comments below.

Until next week

Top comments (0)