RUBY / CHAPTER 02
String mutation and precise matching
IntermediateSeparate normalized copies from changes to shared text.
By the end of this chapter
- Distinguish destructive string methods
- Validate complete strings
- Preserve display values separately from keys
The idea
Ruby strings are mutable objects. Assigning one string variable to another shares the object, while dup creates a separate outer object. Methods such as strip return transformed strings, and their bang counterparts generally modify the receiver. Do not assume every bang method has identical return behavior; some return nil when they make no change. Read the method’s contract before chaining through its result.
Validation should match the complete intended input, not merely find a suitable fragment somewhere inside it. Ruby regular-expression anchors \A and \z describe the absolute beginning and end of a string. This matters when input contains line breaks and line-oriented anchors would accept only one line. Keep a normalized comparison key separate from the original spelling when the interface should retain user-facing text.
raw=" Map "
alias_text=raw
clean=raw.strip
alias_text.replace("Grid")
puts raw
puts cleanGrid Map
The alias mutates the original object, while strip already produced a separate normalized value.
Try it yourself
Validate an ASCII identifier containing only letters and underscores across the entire input.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING