Ruby - Splitting Strings into Arrays

Introduction

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

Demo

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

Result

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:

Demo

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

Result

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:

Demo

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

Result

Related Topic