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"]
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`
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"]
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"]
We can also split at a character.
'kolloioll'.split('o')
# => ["k", "ll", "i", "ll"]
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."]
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"]
"love\x80light".split('')
#=> ArgumentError (invalid byte sequence in UTF-8)
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)