Skip to content

Untie These Chains – A Solution

Earlier I posed the question about why these two similar bits of code do slightly different things:

dim path1 as string = """C:\users\ieuser\desktop\new folder"""
path1 = path1.mid(2)
path1 = path1.left(path1.len()-1)
 
dim path2 as string = """C:\users\ieuser\desktop\new folder"""
path2 = path2.mid(2).left(path2.len()-1)

The issue here is the second bit of code, not the first. In the second each function in the chain returns a result and these results are held in temporary variables with the next function in the chain applied to that. The problem comes with:

left(path2.len()-1)

Why? Because path2 has not been altered yet. It is as if this is evaluated as:

dim path2 as string = """C:\users\ieuser\desktop\new folder"""

dim t1, t2 as string
t1 = path2.mid(2)
t2 = t1.left(path2.len()-1)
path2 = t2

Now you can see the issue. Where we compute t2 we want the altered length to be able to calculate the right number of characters to retain. But we don’t have access to that temporary, so your solution is to do something like this:

dim path2 as string = """C:\users\ieuser\desktop\new folder"""
path2 = path2.mid(2).left(path2.mid(2).len()-1)

And now they both give us the same value!