Minor improvements to error handling and trim the output

This commit is contained in:
runebaas 2019-10-27 12:12:03 +01:00
parent 4e9d1c91ed
commit d2d28b8011
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6

View file

@ -25,17 +25,25 @@ fn main() {
// get fortunes // get fortunes
let filename = matches.value_of("file").unwrap().to_owned(); let filename = matches.value_of("file").unwrap().to_owned();
let fortune_file = fs::read_to_string(filename).unwrap(); let fortune_file = fs::read_to_string(filename).expect("Cannot read fortune file");
let fortunes: Vec<&str> = fortune_file.split('%').collect(); let fortunes: Vec<&str> = fortune_file.split('%').collect();
// filter by max length // filter by max length
let max_length = matches.value_of("length").unwrap().parse::<usize>().unwrap(); let max_length = matches
let filtered = fortunes.into_iter().filter(|x| x.len() < max_length).collect::<Vec<&str>>(); .value_of("length")
.unwrap()
.parse::<usize>()
.expect("Length is not a valid number");
let filtered = fortunes
.into_iter()
.filter(|x| x.replace(" ", "").len() < max_length)
.collect::<Vec<&str>>();
// get a random one // get a random one
let total_fortunes = filtered.len(); let total_fortunes = filtered.len();
let random_fortune = rand::thread_rng().gen_range(0, total_fortunes); let random_fortune = rand::thread_rng().gen_range(0, total_fortunes);
// print // print the fortune
println!("{}", filtered.get(random_fortune).unwrap()); let the_fortune = filtered.get(random_fortune).unwrap().trim();
println!("{}", the_fortune);
} }