Ruby — Parsing strings with partition
Ruby String#partition returns the prefix, matching separator and suffix. Check the middle value to tell a missing separator from a valid empty field.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
parts = "a=b".split("=")
puts parts[1]
b
Split one setting into a key and a value
partition returns the prefix, separator, and suffix. An empty separator signals a missing match. strip trims each side of the pair.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
Ruby 2.7 or later. Run these commands from the directory containing the example.
ruby lesson.rb
key, separator, value = " city = Lima ".partition("=")
puts "#{key.strip}=#{value.strip}" unless separator.empty?
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.