Ruby String#length before slicing
Check that a parcel label contains three characters before taking its depot prefix.
A simple example
String#length before slicing
- Start with Text "A"
- Do this Request a two-character prefix
- Result Too short
Syntax
code.length >= 3
Run these examples in Ruby
Save one example at a time as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rbRead the depot prefix on a damaged label
A parcel scanner expects a three-character depot prefix. A torn label supplies only two characters, so the parcel should go to manual sorting before the software extracts the prefix.
code = "NE"
puts(code.length >= 3 ? code[0, 3] : "Send to manual sorting")
Send to manual sorting
Two letters cannot identify the three-letter depot. The code routes the parcel to a clerk.
Read a complete lab identifier
A student scans a box showing the code BIO7. Extract the three-character prefix. A short scan must be repeated before the record is filed.
Identify an incomplete scan
A label is folded under the scanner and only two letters reach the form. Extract the three-character prefix. A short scan must be repeated before the record is filed.
What to watch for
A substring can be shorter than requested at the end of a String. The depot code here uses ASCII letters.