Loading Text File in Ruby in Windows - ruby

Aptana is returning:
Invalid escape character syntax
File.open("C:\Users\C*****\Documents\RubyProjects\text.txt
What do I do?

\ is an escape charecter in most languages, so the compiler expects an escaped char after it, in this case its also \, so you just need to use 2 of them
File.open("C:\\Users\\C*****\\Documents\\RubyProjects\\text.txt

Ruby doesn't need you to use reverse slashes. In your string
"C:\Users\C*****\Documents\RubyProjects\text.txt"
you're confusing Ruby because you have reverse-slashes, which denote escapes in a double-quoted (interpreted) string and make Ruby throw up. Instead use:
"C:/Users/C*****/Documents/RubyProjects/text.txt"
From the IO documentation:
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb" will be opened as "\gumby\ruby\test.rb". When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"c:\\gumby\\ruby\\test.rb"
Our examples here will use the Unix-style forward slashes; File::ALT_SEPARATOR can be used to get the platform-specific separator character.

Related

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

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:\Users\john\note.txt")
or
File.basename("C:\\Users\\john\\note.txt")
"C:Usersjohn\note.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.
Try pathname:
require 'pathname'
Pathname.new('C:\Users\john\note.txt').basename
# => #<Pathname:note.txt>
Pathname docs
Ref How to get filename without extension from file path in Ruby
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:\Users\john\note.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:Usersjohn\note.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.
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:\Users\john\note.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.

Absolute path in perl's copy command gone wrong?

This is my very simple code, which isn't working, for some reason I can't figure out.
#!/usr/bin/perl
use File::Copy;
$old = "car_lexusisf_gray_30inclination_000azimuth.png";
$new = "C:\Users\Lenovo\Documents\mycomp\simulation\cars\zzzorganizedbyviews\00inclination_000azimuth\lexuscopy.png";
copy ($old, $new) or die "File cannot be copied.";
I get the error that the file can't be copied.
I know there's nothing wrong with the copy command because if I set the value of $new to something simple without a path, it works. But what is wrong in the representation of the path as I've written it above? If I copy and past it into the address bar of windows explorer, it reaches that folder fine.
Tip: print out the paths before you perform the copy. You'll see this:
C:SERSenovodocumentsmycompsimulationrszzzorganizedbyviewsinclination_000azimuthexuscopy.png
Not what we wanted. The backslash is an escape character in Perl, which needs to be escaped itself. If the backslash sequence does not form a valid escape, then it's silently ignored. With escaped backslashes, your string would look like:
"C:\\Users\\Lenovo\\Documents\\mycomp\\simulation\\cars\\zzzorganizedbyviews\\00inclination_000azimuth\\lexuscopy.png";
or just use forward slashes instead – in most cases, Unix-style paths work fine on Windows too.
Here is a list of escapes you accidentally used:
\U uppercases the rest
\L lowercases the rest
\ca is a control character (ASCII 1, the start of heading)
\00 is an octal character, here the NUL byte
\l lowercases the next character.
If no interpolation is intended, use single quotes instead of double quotes.

Take in escaped input in Ruby command line app

I'm writing a Ruby command line application in which the user has to enter a "format string" (much like Date.strptime/strftime's strings).
I tried taking them in as arguments to the command, eg
> torque "%A\n%d\n%i, %u"
but it seems that bash actually removes all backslashes from input before it can be processed (plus a lot of trouble with spaces). I also tried the highline gem, which has some more advanced input options, but that automatically escapes backslashes "\" -> "\\" and provides no alternate options.
My current solution is to do a find-and-replace: "\\n" -> "\n". This would take care of the problem, but it also seems hacky and awful.
I could have users write the string in a text file (complicated for the user) or treat some other character, like "&&", as a newline (still complicated for the user).
What is the best way for users to input escaped characters on the command line?
(UPDATE: I checked the documentation for strptime/strftime, and the format strings for those functions replace newline characters with "%n", tabs with "%t", etc. So for now I'm doing that, but any other suggestions are welcome)
What you're looking for is using single quotes instead of double quotes.
Thus:
> torque '%A\n%d\n%i, %u'
Any string quoted in single quotes 'eg.' is does not go through any expansions and is used as is.
More details can be found in the Quoting section of man bash.
From man bash:
Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
p eval("\"#{gets.chomp}\"")
Example use:
\n\b # Input by the user from the keyboard
"\n\b" # Value from the script
%A\n%d\n%i, %u # Input by the user from the keyboard
"%A\n%d\n%i, %u" # Value from the script

Ruby string with quotes for shell command args?

Hi I need to create string like this:
drawtext="fontfile=/Users/stpn/Documents/Video_Experiments/fonts/Trebuchet_MS.ttf:text='content':fontsize=100:fontcolor=red:y=h/2"
I want to do something like
str = Q%[drawtext="fontfile=/Users/stpn/Documents/Video_Experiments/fonts/Trebuchet_MS.ttf:text='content':fontsize=100:fontcolor=red:y=h/2"]
I am getting this:
=> "drawtext=\"fontfile=/Users/stpn/Documents/Video_Experiments/fonts/Trebuchet_MS.ttf:text='content':fontsize=100:fontcolor=red:y=h/2\""
The escape characters after equals sign in drawtext=" is what I want to get rid of.. How to achieve that?
The string is to be used in a command line args.
Like many languages, Ruby needs a way of delimiting a quoted quote, and the enclosing quotes.
What you're seeing is the escape character which is a way of saying literal quote instead of syntactic quote:
foo = 'test="test"'
# => "test=\"test\""
The escape character is only there because double-quotes are used by default when inspecting a string. It's stored internally as a single character, of course. You may also see these in other circumstances such as a CR+LF delimited file line:
"example_line\r\n"
The \r and \n here correspond with carriage-return and line-feed characters. There's several of these characters defined in ANSI C that have carried over into many languages including Ruby and JavaScript.
When you output a string those escape characters are not displayed:
puts foo
test="test"

How can I escape filenames in ruby (osx) for open/read/hexdigest?

I'm trying to catalog a bunch of files on OSX using ruby, essentially doing this:
hash = Digest::SHA1.hexdigest(File.open(fullpath).read)
This is failing on filenames that contain apostrophes, which are legal characters for a filename.
The File.open works, but I get an "Errno::EINVAL: Invalid argument" error from the read. The filenames are coming directly out of a Dir[] glob.
I've tried escaping them with backslashes, but that doesn't seem to work.
What's the right way to escape these filenames?

Resources