oo1xlw
Last Updated: March 09, 2017
·
38.96K
· stevennunez
148187 557681800912781 556845050 n

Ruby: Convert a string to an array of characters

"This is the bee's knees".scan /\w/
#=> ["T", "h", "i", "s", "i", "s", "t", "h", "e", "b", "e", "e", "s", "k", "n", "e", "e", "s"]

String's #scan will look for anything matching your pattern and return it in an array.

Say Thanks
Respond

7 Responses
Add your response

4102
555155 342136309226266 1457627808 n

You can also do "test".split("")

over 1 year ago ·
4296
148187 557681800912781 556845050 n

That would include spaces, the scan only returns what matches the regex. Nice find!

over 1 year ago ·
15722
320bc95fa1627bd726474622483edf8a

Thank You. I used .scan instead of .split to make a small improvement in this 'Rubymonk module' lesson (second code from the bottom of the page)

https://rubymonk.com/learning/books/1-ruby-primer/chapters/35-modules/lessons/80-modules-as-namespaces#solution4151

over 1 year ago ·
15758
B8f1f9f0a525f8b7b51313056db7fe23

"This is the bee's knees".chars will do the job

over 1 year ago ·
15759
148187 557681800912781 556845050 n

"This is the bee's knees".chars also includes spaces. Using #scan does not include them.

over 1 year ago ·
16451
484f7bcddae423463dc51f23900ea42a

Thank you this was helpful - I actually needed the spaces so thanks @maycry for the .chars tip

over 1 year ago ·
21230
Avatar
"This is the bee's knees".chars.to_a
over 1 year ago ·