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.
Written by Steven Nunez
Related protips
8 Responses
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/58281/555155_342136309226266_1457627808_n.jpg)
You can also do "test".split("")
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/26450/148187_557681800912781_556845050_n.jpg)
That would include spaces, the scan only returns what matches the regex. Nice find!
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/114311/320bc95fa1627bd726474622483edf8a.jpg)
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)
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/114442/b8f1f9f0a525f8b7b51313056db7fe23.png)
"This is the bee's knees".chars will do the job
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/26450/148187_557681800912781_556845050_n.jpg)
"This is the bee's knees".chars also includes spaces. Using #scan does not include them.
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/117271/484f7bcddae423463dc51f23900ea42a.jpeg)
Thank you this was helpful - I actually needed the spaces so thanks @maycry for the .chars tip
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/9540/avatar.png)
"This is the bee's knees".chars.to_a
over 1 year ago
·
"This is the bee's knees".tr(" ' ", "").split.join('').split('') # All chars that may need to be removed from string may be placed in 1st parm of #String.tr method
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#