4 ms·
This is the correct code: def formatted_zip_code(digits) case digits.size when 4 then "0#{digits}" when 3 then "00#{digits}" # 2 or less d
by lifeformed 13y ago
This is the correct code:
def formatted_zip_code(digits)
case digits.size
when 4 then "0#{digits}"
when 3 then "00#{digits}"
# 2 or less digits is an invalid input
else digits
end
end
- nonchalance 13y agoI'd argue that, since the comment regards valid input, the note should appear at the top.
- pnathan 13y agoI'd improve that because of this: -> if the argument doesn't conform to contract, an assert/exception should be thrown so that the caller can recognize the existence of an incorrectly used function.
- dekz 13y agoAre there zip codes that are 2 digits? I'd fall fallacy to this post and once again argue to the contrary. If this function is about formatting zip codes with leading zeros, and zip codes are either 4 or 3 digits. Why would an invalid zip code be passed to this method, a formatter? Normally I'd agree with your argument about failing to meet a contract, but why would this formatter method get anything but a valid zip code.
- nonchalance 13y agoThe first 3 digits of a zip code represent the sectional center facility code, the smallest of which is 005. One would assume that 00501 is the smallest zip code (which apparently maps to HOLTSVILLE NY ) http://pe.usps.com/text/LabelingLists/L002.htm#xd_L002 http://pe.usps.com/text/LabelingLists/L002.htm#xd_L002 https://tools.usps.com/go/ZipLookupAction!input.action https://tools.usps.com/go/ZipLookupAction!input.action
- pnathan 13y ago> why would this formatter method get anything but a valid zip code. Ask not, lest ye receive an answer. Seriously speaking, you can't trust that callers will be sane unless you establish a priori with a higher level contract that all possible callers will be sane.