How to obtain basename in ruby from the given file path in unix or windows format? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How to get filename without extension from file path in RubyHow can I “pretty” format my JSON output in Ruby on Rails?How to break out from a ruby block?Extract file basename without path and extension in bashHow to write to file in Ruby?Given two directory trees, how can I find out which files differ?How to get full path of a file?How to remove a key from Hash and get the remaining hash in Ruby/Rails?How to download a file from server using SSH?How to permanently set $PATH on Linux/Unix?How do I copy folder with files to another folder in Unix/Linux?

Can anything be seen from the center of the Boötes void? How dark would it be?

Morning, Afternoon, Night Kanji

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

Time to Settle Down!

Is it possible for SQL statements to execute concurrently within a single session in SQL Server?

How do I change colors in Zim (wiki editor) running on Kubuntu 18.10?

Generate an RGB colour grid

What's the meaning of "fortified infraction restraint"?

Take 2! Is this homebrew Lady of Pain warlock patron balanced?

How to react to hostile behavior from a senior developer?

How does the secondary effect of the Heat Metal spell interact with a creature resistant/immune to fire damage?

Do I really need to have a message in a novel to appeal to readers?

If Windows 7 doesn't support WSL, then what does Linux subsystem option mean?

How to compare two different files line by line in unix?

What order were files/directories outputted in dir?

How to tell that you are a giant?

Sum letters are not two different

Why weren't discrete x86 CPUs ever used in game hardware?

Why is the AVR GCC compiler using a full `CALL` even though I have set the `-mshort-calls` flag?

How could we fake a moon landing now?

ArcGIS Pro Python arcpy.CreatePersonalGDB_management

Why do early math courses focus on the cross sections of a cone and not on other 3D objects?

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

What is the difference between globalisation and imperialism?



How to obtain basename in ruby from the given file path in unix or windows format?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How to get filename without extension from file path in RubyHow can I “pretty” format my JSON output in Ruby on Rails?How to break out from a ruby block?Extract file basename without path and extension in bashHow to write to file in Ruby?Given two directory trees, how can I find out which files differ?How to get full path of a file?How to remove a key from Hash and get the remaining hash in Ruby/Rails?How to download a file from server using SSH?How to permanently set $PATH on Linux/Unix?How do I copy folder with files to another folder in Unix/Linux?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I need to parse a basename in ruby a from file path which I get as input. Unix format works fine on Linux.



File.basename("/tmp/text.txt")


return "text.txt".

However, when I get input in windows format:



File.basename("C:Usersjohnnote.txt")


or



File.basename("C:\Users\john\note.txt")


"C:Usersjohnnote.txt" is the output (note that n is a new line there), but I didn't get "note.txt".



Is there some nice solution in ruby/rails?



Solution:



"C:\test\note.txt".split(/\|//).last
=> "note.txt"
"/tmp/test/note.txt".split(/\|//).last
=> "note.txt"


If the Linux file name doesn't contain , it will work.










share|improve this question
























  • Note: "C:U".chars #=> ["C", ":", "U"].

    – Cary Swoveland
    Mar 8 at 20:54







  • 1





    @CarySwoveland Further note "note" is treated as new line character (n) ote.txt.

    – engineersmnky
    Mar 8 at 21:19


















0















I need to parse a basename in ruby a from file path which I get as input. Unix format works fine on Linux.



File.basename("/tmp/text.txt")


return "text.txt".

However, when I get input in windows format:



File.basename("C:Usersjohnnote.txt")


or



File.basename("C:\Users\john\note.txt")


"C:Usersjohnnote.txt" is the output (note that n is a new line there), but I didn't get "note.txt".



Is there some nice solution in ruby/rails?



Solution:



"C:\test\note.txt".split(/\|//).last
=> "note.txt"
"/tmp/test/note.txt".split(/\|//).last
=> "note.txt"


If the Linux file name doesn't contain , it will work.










share|improve this question
























  • Note: "C:U".chars #=> ["C", ":", "U"].

    – Cary Swoveland
    Mar 8 at 20:54







  • 1





    @CarySwoveland Further note "note" is treated as new line character (n) ote.txt.

    – engineersmnky
    Mar 8 at 21:19














0












0








0








I need to parse a basename in ruby a from file path which I get as input. Unix format works fine on Linux.



File.basename("/tmp/text.txt")


return "text.txt".

However, when I get input in windows format:



File.basename("C:Usersjohnnote.txt")


or



File.basename("C:\Users\john\note.txt")


"C:Usersjohnnote.txt" is the output (note that n is a new line there), but I didn't get "note.txt".



Is there some nice solution in ruby/rails?



Solution:



"C:\test\note.txt".split(/\|//).last
=> "note.txt"
"/tmp/test/note.txt".split(/\|//).last
=> "note.txt"


If the Linux file name doesn't contain , it will work.










share|improve this question
















I need to parse a basename in ruby a from file path which I get as input. Unix format works fine on Linux.



File.basename("/tmp/text.txt")


return "text.txt".

However, when I get input in windows format:



File.basename("C:Usersjohnnote.txt")


or



File.basename("C:\Users\john\note.txt")


"C:Usersjohnnote.txt" is the output (note that n is a new line there), but I didn't get "note.txt".



Is there some nice solution in ruby/rails?



Solution:



"C:\test\note.txt".split(/\|//).last
=> "note.txt"
"/tmp/test/note.txt".split(/\|//).last
=> "note.txt"


If the Linux file name doesn't contain , it will work.







ruby linux ruby-on-rails-3






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 14 at 20:07







malmed

















asked Mar 8 at 20:41









malmedmalmed

3021410




3021410












  • Note: "C:U".chars #=> ["C", ":", "U"].

    – Cary Swoveland
    Mar 8 at 20:54







  • 1





    @CarySwoveland Further note "note" is treated as new line character (n) ote.txt.

    – engineersmnky
    Mar 8 at 21:19


















  • Note: "C:U".chars #=> ["C", ":", "U"].

    – Cary Swoveland
    Mar 8 at 20:54







  • 1





    @CarySwoveland Further note "note" is treated as new line character (n) ote.txt.

    – engineersmnky
    Mar 8 at 21:19

















Note: "C:U".chars #=> ["C", ":", "U"].

– Cary Swoveland
Mar 8 at 20:54






Note: "C:U".chars #=> ["C", ":", "U"].

– Cary Swoveland
Mar 8 at 20:54





1




1





@CarySwoveland Further note "note" is treated as new line character (n) ote.txt.

– engineersmnky
Mar 8 at 21:19






@CarySwoveland Further note "note" is treated as new line character (n) ote.txt.

– engineersmnky
Mar 8 at 21:19













3 Answers
3






active

oldest

votes


















0














Backslashes, while how Windows expresses things, are just a giant nuisance. Within a double-quoted string they have special meaning so you either need to do:



File.basename("C:\Users\john\note.txt")


Or use single quotes that avoid the issue:



File.basename('C:Usersjohnnote.txt')


Or use regular slashes which aren't impacted:



File.basename("C:/Users/john/note.txt")


Where Ruby does the mapping for you to the platform-specific path separator.






share|improve this answer























  • The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

    – Sergio Tulentsev
    Mar 11 at 10:38












  • It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

    – malmed
    Mar 11 at 11:07


















1














Try pathname:



require 'pathname'

Pathname.new('C:Usersjohnnote.txt').basename
# => #<Pathname:note.txt>


Pathname docs



Ref How to get filename without extension from file path in Ruby






share|improve this answer


















  • 1





    @CarySwoveland what do you mean?

    – Martin Zinovsky
    Mar 8 at 20:58






  • 2





    The OP used double quotes without escaping the backslash.

    – Cary Swoveland
    Mar 8 at 20:59






  • 1





    This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

    – engineersmnky
    Mar 8 at 21:05











  • @engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

    – tadman
    Mar 8 at 22:28











  • @tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

    – engineersmnky
    Mar 8 at 22:37


















1














I'm not convinced that you have a problem with your code. I think you have a problem with your test.



Ruby also uses the backslash character for escape sequences in strings, so when you type the String literal "C:Usersjohnnote.txt", Ruby sees the first two backslashes as invalid escape sequences, and so ignores the escape character. n refers to a newline. So, to Ruby, this literal is the same as "C:Usersjohnnote.txt". There aren't any file separators in that sequence, since n is a newline, not a backslash followed by the letter n, so File.basename just returns it as it receives it.



If you ask for user input in either a graphical user interface (GUI) or command line interface (CLI), the user entering input needn't worry about Ruby String escape sequences; those only matter for String literals directly in the code. Try it! Type gets into IRB or Pry, and type or copy a file path, and press Enter, and see how Ruby displays it as a String literal.



On Windows, Ruby accepts paths given using both "/" (File::SEPARATOR) and "\" (File::ALT_SEPARATOR), so you don't need to worry about conversion unless you are displaying it to the user.






share|improve this answer























  • You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

    – malmed
    Mar 11 at 10:46











  • @malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

    – sondra.kinsey
    Mar 13 at 18:05











  • I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

    – malmed
    Mar 14 at 19:55











  • @malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

    – sondra.kinsey
    Mar 14 at 20:04











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55070700%2fhow-to-obtain-basename-in-ruby-from-the-given-file-path-in-unix-or-windows-forma%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Backslashes, while how Windows expresses things, are just a giant nuisance. Within a double-quoted string they have special meaning so you either need to do:



File.basename("C:\Users\john\note.txt")


Or use single quotes that avoid the issue:



File.basename('C:Usersjohnnote.txt')


Or use regular slashes which aren't impacted:



File.basename("C:/Users/john/note.txt")


Where Ruby does the mapping for you to the platform-specific path separator.






share|improve this answer























  • The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

    – Sergio Tulentsev
    Mar 11 at 10:38












  • It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

    – malmed
    Mar 11 at 11:07















0














Backslashes, while how Windows expresses things, are just a giant nuisance. Within a double-quoted string they have special meaning so you either need to do:



File.basename("C:\Users\john\note.txt")


Or use single quotes that avoid the issue:



File.basename('C:Usersjohnnote.txt')


Or use regular slashes which aren't impacted:



File.basename("C:/Users/john/note.txt")


Where Ruby does the mapping for you to the platform-specific path separator.






share|improve this answer























  • The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

    – Sergio Tulentsev
    Mar 11 at 10:38












  • It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

    – malmed
    Mar 11 at 11:07













0












0








0







Backslashes, while how Windows expresses things, are just a giant nuisance. Within a double-quoted string they have special meaning so you either need to do:



File.basename("C:\Users\john\note.txt")


Or use single quotes that avoid the issue:



File.basename('C:Usersjohnnote.txt')


Or use regular slashes which aren't impacted:



File.basename("C:/Users/john/note.txt")


Where Ruby does the mapping for you to the platform-specific path separator.






share|improve this answer













Backslashes, while how Windows expresses things, are just a giant nuisance. Within a double-quoted string they have special meaning so you either need to do:



File.basename("C:\Users\john\note.txt")


Or use single quotes that avoid the issue:



File.basename('C:Usersjohnnote.txt')


Or use regular slashes which aren't impacted:



File.basename("C:/Users/john/note.txt")


Where Ruby does the mapping for you to the platform-specific path separator.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 22:30









tadmantadman

158k19182211




158k19182211












  • The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

    – Sergio Tulentsev
    Mar 11 at 10:38












  • It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

    – malmed
    Mar 11 at 11:07

















  • The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

    – Sergio Tulentsev
    Mar 11 at 10:38












  • It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

    – malmed
    Mar 11 at 11:07
















The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

– Sergio Tulentsev
Mar 11 at 10:38






The first two didn't work for me on macos. Because of File::SEPARATOR, I assume. So, short of running this code on windows. the caller has to convert the slashes as a pre-processing step. :shrug:

– Sergio Tulentsev
Mar 11 at 10:38














It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

– malmed
Mar 11 at 11:07





It seems that the only way is substitute ` and ` to / and then parse it as Unix file path. Or mess up with File::ALT_SEPARATOR. Anyway, it will change Unix file names like /tmp/testfile.txt :(

– malmed
Mar 11 at 11:07













1














Try pathname:



require 'pathname'

Pathname.new('C:Usersjohnnote.txt').basename
# => #<Pathname:note.txt>


Pathname docs



Ref How to get filename without extension from file path in Ruby






share|improve this answer


















  • 1





    @CarySwoveland what do you mean?

    – Martin Zinovsky
    Mar 8 at 20:58






  • 2





    The OP used double quotes without escaping the backslash.

    – Cary Swoveland
    Mar 8 at 20:59






  • 1





    This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

    – engineersmnky
    Mar 8 at 21:05











  • @engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

    – tadman
    Mar 8 at 22:28











  • @tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

    – engineersmnky
    Mar 8 at 22:37















1














Try pathname:



require 'pathname'

Pathname.new('C:Usersjohnnote.txt').basename
# => #<Pathname:note.txt>


Pathname docs



Ref How to get filename without extension from file path in Ruby






share|improve this answer


















  • 1





    @CarySwoveland what do you mean?

    – Martin Zinovsky
    Mar 8 at 20:58






  • 2





    The OP used double quotes without escaping the backslash.

    – Cary Swoveland
    Mar 8 at 20:59






  • 1





    This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

    – engineersmnky
    Mar 8 at 21:05











  • @engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

    – tadman
    Mar 8 at 22:28











  • @tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

    – engineersmnky
    Mar 8 at 22:37













1












1








1







Try pathname:



require 'pathname'

Pathname.new('C:Usersjohnnote.txt').basename
# => #<Pathname:note.txt>


Pathname docs



Ref How to get filename without extension from file path in Ruby






share|improve this answer













Try pathname:



require 'pathname'

Pathname.new('C:Usersjohnnote.txt').basename
# => #<Pathname:note.txt>


Pathname docs



Ref How to get filename without extension from file path in Ruby







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 20:50









Martin ZinovskyMartin Zinovsky

1,79411017




1,79411017







  • 1





    @CarySwoveland what do you mean?

    – Martin Zinovsky
    Mar 8 at 20:58






  • 2





    The OP used double quotes without escaping the backslash.

    – Cary Swoveland
    Mar 8 at 20:59






  • 1





    This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

    – engineersmnky
    Mar 8 at 21:05











  • @engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

    – tadman
    Mar 8 at 22:28











  • @tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

    – engineersmnky
    Mar 8 at 22:37












  • 1





    @CarySwoveland what do you mean?

    – Martin Zinovsky
    Mar 8 at 20:58






  • 2





    The OP used double quotes without escaping the backslash.

    – Cary Swoveland
    Mar 8 at 20:59






  • 1





    This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

    – engineersmnky
    Mar 8 at 21:05











  • @engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

    – tadman
    Mar 8 at 22:28











  • @tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

    – engineersmnky
    Mar 8 at 22:37







1




1





@CarySwoveland what do you mean?

– Martin Zinovsky
Mar 8 at 20:58





@CarySwoveland what do you mean?

– Martin Zinovsky
Mar 8 at 20:58




2




2





The OP used double quotes without escaping the backslash.

– Cary Swoveland
Mar 8 at 20:59





The OP used double quotes without escaping the backslash.

– Cary Swoveland
Mar 8 at 20:59




1




1





This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

– engineersmnky
Mar 8 at 21:05





This does not seem to work in linux using 2.6.1 Pathname.new('C:Usersjohnnote.txt').basename #=> #<Pathname:C:Usersjohnnote.txt>

– engineersmnky
Mar 8 at 21:05













@engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

– tadman
Mar 8 at 22:28





@engineersmnky It won't work in Linux because Linux doesn't treat the backslash the same way as Windows does.

– tadman
Mar 8 at 22:28













@tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

– engineersmnky
Mar 8 at 22:37





@tadman my point was more that it is unlikely a rails server is running over IIS so this may not be a viable option

– engineersmnky
Mar 8 at 22:37











1














I'm not convinced that you have a problem with your code. I think you have a problem with your test.



Ruby also uses the backslash character for escape sequences in strings, so when you type the String literal "C:Usersjohnnote.txt", Ruby sees the first two backslashes as invalid escape sequences, and so ignores the escape character. n refers to a newline. So, to Ruby, this literal is the same as "C:Usersjohnnote.txt". There aren't any file separators in that sequence, since n is a newline, not a backslash followed by the letter n, so File.basename just returns it as it receives it.



If you ask for user input in either a graphical user interface (GUI) or command line interface (CLI), the user entering input needn't worry about Ruby String escape sequences; those only matter for String literals directly in the code. Try it! Type gets into IRB or Pry, and type or copy a file path, and press Enter, and see how Ruby displays it as a String literal.



On Windows, Ruby accepts paths given using both "/" (File::SEPARATOR) and "\" (File::ALT_SEPARATOR), so you don't need to worry about conversion unless you are displaying it to the user.






share|improve this answer























  • You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

    – malmed
    Mar 11 at 10:46











  • @malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

    – sondra.kinsey
    Mar 13 at 18:05











  • I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

    – malmed
    Mar 14 at 19:55











  • @malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

    – sondra.kinsey
    Mar 14 at 20:04















1














I'm not convinced that you have a problem with your code. I think you have a problem with your test.



Ruby also uses the backslash character for escape sequences in strings, so when you type the String literal "C:Usersjohnnote.txt", Ruby sees the first two backslashes as invalid escape sequences, and so ignores the escape character. n refers to a newline. So, to Ruby, this literal is the same as "C:Usersjohnnote.txt". There aren't any file separators in that sequence, since n is a newline, not a backslash followed by the letter n, so File.basename just returns it as it receives it.



If you ask for user input in either a graphical user interface (GUI) or command line interface (CLI), the user entering input needn't worry about Ruby String escape sequences; those only matter for String literals directly in the code. Try it! Type gets into IRB or Pry, and type or copy a file path, and press Enter, and see how Ruby displays it as a String literal.



On Windows, Ruby accepts paths given using both "/" (File::SEPARATOR) and "\" (File::ALT_SEPARATOR), so you don't need to worry about conversion unless you are displaying it to the user.






share|improve this answer























  • You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

    – malmed
    Mar 11 at 10:46











  • @malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

    – sondra.kinsey
    Mar 13 at 18:05











  • I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

    – malmed
    Mar 14 at 19:55











  • @malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

    – sondra.kinsey
    Mar 14 at 20:04













1












1








1







I'm not convinced that you have a problem with your code. I think you have a problem with your test.



Ruby also uses the backslash character for escape sequences in strings, so when you type the String literal "C:Usersjohnnote.txt", Ruby sees the first two backslashes as invalid escape sequences, and so ignores the escape character. n refers to a newline. So, to Ruby, this literal is the same as "C:Usersjohnnote.txt". There aren't any file separators in that sequence, since n is a newline, not a backslash followed by the letter n, so File.basename just returns it as it receives it.



If you ask for user input in either a graphical user interface (GUI) or command line interface (CLI), the user entering input needn't worry about Ruby String escape sequences; those only matter for String literals directly in the code. Try it! Type gets into IRB or Pry, and type or copy a file path, and press Enter, and see how Ruby displays it as a String literal.



On Windows, Ruby accepts paths given using both "/" (File::SEPARATOR) and "\" (File::ALT_SEPARATOR), so you don't need to worry about conversion unless you are displaying it to the user.






share|improve this answer













I'm not convinced that you have a problem with your code. I think you have a problem with your test.



Ruby also uses the backslash character for escape sequences in strings, so when you type the String literal "C:Usersjohnnote.txt", Ruby sees the first two backslashes as invalid escape sequences, and so ignores the escape character. n refers to a newline. So, to Ruby, this literal is the same as "C:Usersjohnnote.txt". There aren't any file separators in that sequence, since n is a newline, not a backslash followed by the letter n, so File.basename just returns it as it receives it.



If you ask for user input in either a graphical user interface (GUI) or command line interface (CLI), the user entering input needn't worry about Ruby String escape sequences; those only matter for String literals directly in the code. Try it! Type gets into IRB or Pry, and type or copy a file path, and press Enter, and see how Ruby displays it as a String literal.



On Windows, Ruby accepts paths given using both "/" (File::SEPARATOR) and "\" (File::ALT_SEPARATOR), so you don't need to worry about conversion unless you are displaying it to the user.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 10 at 8:32









sondra.kinseysondra.kinsey

14910




14910












  • You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

    – malmed
    Mar 11 at 10:46











  • @malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

    – sondra.kinsey
    Mar 13 at 18:05











  • I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

    – malmed
    Mar 14 at 19:55











  • @malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

    – sondra.kinsey
    Mar 14 at 20:04

















  • You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

    – malmed
    Mar 11 at 10:46











  • @malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

    – sondra.kinsey
    Mar 13 at 18:05











  • I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

    – malmed
    Mar 14 at 19:55











  • @malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

    – sondra.kinsey
    Mar 14 at 20:04
















You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

– malmed
Mar 11 at 10:46





You are right with gets -> "C:\Users\john\note.txtn". However, in Linux Ruby/Rails File nor Pathname cannot parse it.

– malmed
Mar 11 at 10:46













@malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

– sondra.kinsey
Mar 13 at 18:05





@malmed: I'm not on Windows right now, so I can't check, but I'm fairly sure that both File and Pathname should handle "C:\Users\john\note.txt" just fine. I suspect it is the trailing newline (n) that is causing your problem. Use String#chop.

– sondra.kinsey
Mar 13 at 18:05













I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

– malmed
Mar 14 at 19:55





I'm also not on Windows (but I receive both formats of a path). I don't doubt, that "C:\Users\john\note.txt" is parsed fine on Windows.

– malmed
Mar 14 at 19:55













@malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

– sondra.kinsey
Mar 14 at 20:04





@malmed Are you saying that you want a user to input a file path into a web application, and then have your app manipulate that path? I'm having a hard time imagining a use case for that. Obviously, you can just use String#split.

– sondra.kinsey
Mar 14 at 20:04

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55070700%2fhow-to-obtain-basename-in-ruby-from-the-given-file-path-in-unix-or-windows-forma%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved