How can I write a Ruby function that splits the input by any kind of whitespace, and remove all the whitespace from the result? For example, if the input is
aa bbb
cc dd ee
Then return an array ["aa", "bbb", "cc", "dd", "ee"].
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The following should work for the example you gave:
it returns:
Meaning of code:
/\s+/mis the more complicated part.\smeans white space, so\s+means one ore more white space letters. In the/mpart,mis called a modifier, in this case it means, multiline, meaning visit many lines, not just one which is the default behavior.So,
/\s+/mmeans, find sequences of one or more white spaces.gsubmeans replace all.stripis the equivalent oftrimin other languages, and removes spaces from the front and end of the string.As, I was writing the explanation, it could be the case where you do end up with and end-line character at the end or the beginning of the string.
To be safe
The code could be written as:
So if you had:
Then you’d get:
Meaning of new code:
^\s+a sequence of white spaces at the beginning of the string\s+$a sequence of white spaces at the end of the stringSo
gsub(/^\s+|\s+$/m, '')means remove any sequence of white space at the beginning of the string and at the end of the string.