Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Newbie: unexpected result with string.split( regexpr )

Reply
Thread Tools

Newbie: unexpected result with string.split( regexpr )

 
 
francisrammeloo@hotmail.com
Guest
Posts: n/a
 
      07-28-2005
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

 
Reply With Quote
 
 
 
 
Austin Ziegler
Guest
Posts: n/a
 
      07-28-2005
On 7/28/05, http://www.velocityreviews.com/forums/(E-Mail Removed) <(E-Mail Removed)> wrote=
:
> 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 Removed)
* Alternate: (E-Mail Removed)


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Mysql::Result .each_hash - unexpected result Andy Tolle Ruby 7 11-15-2010 10:39 AM
1. Ruby result: 101 seconds , 2. Java result:9.8 seconds, 3. Perl result:62 seconds Michael Tan Ruby 32 07-21-2005 03:23 PM
Regexpr FTP MC Perl 4 02-09-2005 03:23 AM
function return value in a regexpr Jonas Perl 3 08-11-2004 09:12 PM
regexpr question is w2 taken Richard Bell Perl Misc 3 04-16-2004 11:48 AM



Advertisments