Breaking Down the Split

A comprehensive guide to Ruby’s split method

Waverley Leung
Sep 10, 2020 · 6 min read
Image for post
Image for post
Photo by Chris Ried on Unsplash

Table of Contents

Introduction

Vocabulary Review 👀

So…what is the split method exactly? 🤔

array = string.split(pattern, limit)

What can I do with the split method? ✍🏼

Split with NO pattern and/or limit:

" now's  the time    ".split #=> ["now's", "the", "time"]

Split with ONLY pattern:

" now's  the time".split(' ') #=> ["now's", "the", "time"]"mellow yellow".split("ello") #=> ["m", "w y", "w"]"1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"]
" now's  the time".split(/ /) #=> ["", "now's", "", "the", "time"]"hello".split(//) #=> ["h", "e", "l", "l", "o"]"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]"hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"]

Split with pattern AND limit:

"hello".split(//, 3) #=> ["h", "e", "llo"]"1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""]
"mellow yellow".split("ello", 1) #=> ["mellow yellow"]

Something to put out there…

"".split(',', -1) #=> []

Conclusion & Takeaways 📝

The Startup

Medium's largest active publication, followed by +752K people. Follow to join our community.

Waverley Leung

Written by

“Be present. Be open. Be kind. But speak your mind.” 🌱 Passionate about tech, connecting with people, eating good food, and dancing to my heart’s content.

The Startup

Medium's largest active publication, followed by +752K people. Follow to join our community.

Waverley Leung

Written by

“Be present. Be open. Be kind. But speak your mind.” 🌱 Passionate about tech, connecting with people, eating good food, and dancing to my heart’s content.

The Startup

Medium's largest active publication, followed by +752K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store