Newbie: unexpected result with string.split( regexpr )

Discussion in 'Ruby' started by francisrammeloo@hotmail.com, Jul 28, 2005.

  1. Guest

    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
    , Jul 28, 2005
    #1
    1. Advertising

  2. On 7/28/05, <> 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 *
    * Alternate:
    Austin Ziegler, Jul 28, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jonas
    Replies:
    3
    Views:
    366
    Gunnar Hjalmarsson
    Aug 11, 2004
  2. MC

    Regexpr FTP

    MC, Feb 4, 2005, in forum: Perl
    Replies:
    4
    Views:
    540
    Martin Gregory
    Feb 9, 2005
  3. Michael Tan
    Replies:
    32
    Views:
    937
    Ara.T.Howard
    Jul 21, 2005
  4. Andy Tolle
    Replies:
    7
    Views:
    222
    Andy Tolle
    Nov 15, 2010
  5. Richard Bell

    regexpr question is w2 taken

    Richard Bell, Apr 15, 2004, in forum: Perl Misc
    Replies:
    3
    Views:
    97
    Anno Siegel
    Apr 16, 2004
Loading...

Share This Page