Skip to content

Instantly share code, notes, and snippets.

@wperron
Created September 26, 2022 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/91c64c868c99b89cdc4f7019e88614ec to your computer and use it in GitHub Desktop.
Save wperron/91c64c868c99b89cdc4f7019e88614ec to your computer and use it in GitHub Desktop.
Return a string corresponding to the ordinal of the given integer using Rust's pattern matching
fn main() {
println!("Hello, world!");
}
pub fn ordinal(num: isize) -> String {
let one = num % 10;
let ten = (num / 10) % 10;
match (one, ten) {
(o, t) if t == 1 && o > 0 && 0 <= 3 => format!("{}th", num),
(1, _) => format!("{}st", num),
(2, _) => format!("{}nd", num),
(3, _) => format!("{}rd", num),
(_, _) => format!("{}th", num),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_ordinal() {
assert_eq!("1st", ordinal(1));
assert_eq!("2nd", ordinal(2));
assert_eq!("3rd", ordinal(3));
assert_eq!("4th", ordinal(4));
assert_eq!("6th", ordinal(6));
assert_eq!("7th", ordinal(7));
assert_eq!("10th", ordinal(10));
assert_eq!("11th", ordinal(11));
assert_eq!("12th", ordinal(12));
assert_eq!("13th", ordinal(13));
assert_eq!("21st", ordinal(21));
assert_eq!("22nd", ordinal(22));
assert_eq!("23rd", ordinal(23));
assert_eq!("111th", ordinal(111));
assert_eq!("112th", ordinal(112));
assert_eq!("913th", ordinal(913));
assert_eq!("10012th", ordinal(10012));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment