Library contents

Ruby String#partition

String#partition returns three strings containing the text before the match, the match itself, and the text after it.

A simple example

String#partition

  1. Start with "a=b"
  2. Do this Partition at the equals sign
  3. Result "a", "=", "b"
Partition keeps the matched separator between the two surrounding pieces.

Syntax

Ruby syntax
key, separator, value = field.partition('=')
Run this example in Ruby

Save the program as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Split a setting at its first equals sign

A configuration line separates a key from its value with punctuation. Split only at the first intended boundary because the value itself may contain the same separator later on.

From the program['token=a=b', 'mode=', 'broken'].each do |field|
First output linetoken [a=b]
lesson.rb
['token=a=b', 'mode=', 'broken'].each do |field|
  key, separator, value = field.partition('=')
  puts separator.empty? ? 'missing separator' : "#{key} [#{value}]"
end
Output
token [a=b]
mode []
missing separator

An empty separator marks an absent equals sign. When the separator is present, the value may legitimately be empty or contain another equals sign.

Ruby documentation for String#partition

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The desk separates zero-quantity records for review. How many positive entries remain in the other group?

Given6 · 2 · 6 · 0
Worked result3

Review print quantities

A print room records four job quantities, including a cancelled job. The desk separates zero-quantity records for review. How many positive entries remain in the other group?

Given3 · 0 · 8 · 3
Worked result3