Ruby - Splitting Strings into Arrays


scan method without a block of code returns an array of all the matching parts of the string:


puts "This is a test".scan(/\w/).join(',')


First you define a string literal, then you scan over it for alphanumeric characters using /\w/.

Finally you join the elements of the returned array together with commas.

split method splits a string into an array of strings on the periods:


puts "this. is. a. test.".split(/\./).inspect


If you'd used . in the regular expression rather than \., you'd be splitting on every character rather than on full stops.

. represents "any character" in a regular expression.

To escape it by prefixing it with a backslash.

inspect method is common to almost all built-in classes in Ruby and it gives you a textual representation of the object.

split can split on newlines, or multiple characters at once, to get a cleaner result:


puts "this is a test".split(/\s+/).inspect


Related Topic