Today I Learned

hashrocket A Hashrocket project

Ruby Partition Methods

One cool way to chop through a Ruby string is the partition String method. This uses regex to search for a match in a string. If it finds one, it returns what came before the match, the match, and what came after as elements in an array.

2.2.2 :001 > 'foo bar baz bat'.partition 'bar'
 => ["foo ", "bar", " baz bat"]

This is not to be confused with the partition Array method, which takes a block. Any elements that evaluate true are returned first, followed by the elements that evaluate false.

2.2.2 :002 > [1,2,3,4,5].partition(&:even?)
 => [[2, 4], [1, 3, 5]]
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.