#Getting the last n elements of a path and print them with join("/")

6 messages · Page 1 of 1 (latest)

sonic matrix
#

I tried using this abomination:

let current_dir = env::current_dir().unwrap();

let dir_components = current_dir.components();

let dir_components_vec = dir_components.collect::<Vec<_>>();
let last_components = 
            dir_components_vec.iter()
            .rev()
            .take(n)
            .collect::<Vec<_>>()
            .into_iter()
            .map(|&dir| dir.as_os_str().to_str())
            .collect::<Vec<_>>()
            .join('/'));

but it returns this error:

join method cannot be called on `Vec<Option<&str>>` due to unsatisfied trait bounds
note: the following trait bounds were not satisfied:
[Option<&str>]: Join<_>

I tried using .try_into but the compiler told me to specify a type and I had know idea what type I need to convert the value into

limpid jewel
# sonic matrix I tried using this abomination: ```rust let current_dir = env::current_dir().unw...

?play

// idk if this is best, but it does something:

use std::env;
use std::path::Path;

fn main() {
    let n = 2;

    let current_dir = env::current_dir().unwrap();
    
    let num_components = current_dir.components().count();
    let mut components_iter = current_dir.components();
    for _ in 0..(num_components - n) {
        components_iter.next();
    }
    let last_components = components_iter.as_path();

        
    println!("{last_components:?}")
}
scarlet vergeBOT
#
"/playground"```
limpid jewel
#

FYI, the .components() method and the .iter() method on Path do different things.

sonic matrix
#

Thank you, at this point anything that works is fine, I've never thought of using iterators like that