Newbie: unexpected result with string.split( regexpr )

F

francisrammeloo

Hi all,

My goal is to obtain the filename out of a full pathname.

This is the code:

fullname = "./Dir/file.txt"
array = fullname.split( /.*\// ) # Searches greedyly until the last
slash


The results are:

puts array.length ==> 2
puts array[0] ==> (newline symbol or something??)
puts array[1] ==> file.txt


My questions are:

Why has the array a length of 2?
What is in array[0]?


Best regards,
Francis
 
A

Austin Ziegler

My goal is to obtain the filename out of a full pathname.
=20
This is the code:
fullname =3D "./Dir/file.txt"
# Searches greedyly until the last slash
array =3D fullname.split(/.*\//)
=20
The results are:
puts array.length =3D=3D> 2
puts array[0] =3D=3D> (newline symbol or something??)
puts array[1] =3D=3D> file.txt
=20
My questions are:
Why has the array a length of 2?
What is in array[0]?

Because you're splitting, not matching.

./Dir/file.txt
^^^^^^ <-- What's here is your separator.

There's nothing *before* your separator, so array[0] is an empty
string; array[1] is the filename. There are two ways that are
better:

fullname =3D "./Dir/file.txt"
# Alternate regex form to avoid escaping.
array =3D fullname.split(%r{/}, -1)
puts array.length, array[-1]

# Best way
puts File.basename(fullname)

-austin
--=20
Austin Ziegler * (e-mail address removed)
* Alternate: (e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top