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
- Start with "a=b"
- Do this Partition at the equals sign
- Result "a", "=", "b"
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.
['token=a=b', 'mode=', 'broken'].each do |field|
key, separator, value = field.partition('=')
puts separator.empty? ? 'missing separator' : "#{key} [#{value}]"
end
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
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?
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?