How to obtain basename in ruby from the given file path in unix or windows format?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?

Implication of namely

How to remove border from elements in the last row?

How can I prove that a state of equilibrium is unstable?

Could neural networks be considered metaheuristics?

Is this draw by repetition?

How dangerous is XSS

Did 'Cinema Songs' exist during Hiranyakshipu's time?

Does the Idaho Potato Commission associate potato skins with healthy eating?

What is the opposite of "eschatology"?

How can saying a song's name be a copyright violation?

Unlock My Phone! February 2018

What are the G forces leaving Earth orbit?

Finitely generated matrix groups whose eigenvalues are all algebraic

Pact of Blade Warlock with Dancing Blade

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

Is it "common practice in Fourier transform spectroscopy to multiply the measured interferogram by an apodizing function"? If so, why?

Do creatures with a speed 0ft., fly 30ft. (hover) ever touch the ground?

What does the same-ish mean?

What is an equivalently powerful replacement spell for Yuan-Ti's Suggestion spell?

Finding the reason behind the value of the integral.

Car headlights in a world without electricity

How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?

What is the fastest integer factorization to break RSA?

In the UK, is it possible to get a referendum by a court decision?



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


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?













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

1921210




1921210












  • 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

157k19181210




157k19181210












  • 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,72711017




1,72711017







  • 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

14810




14810












  • 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

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page