How could I have the output of say the unix 'ls' (Desktop, Pictures, Music myysong.mp3 etc) be converted to a string?? thx in advance
The backtick executes a system command and returns it output as a string.
result = `ls ~/Downloads`
puts result.reverse
puts result.split('/')
Do you mean capture the output of the 'ls' command? You can use `` in Ruby. Eg:
mystring = `ls <dir>`
print mystring.strip();
So, I thought I would edit my previous answer. If you are unfortunate enough to come across an error in the ls command (say the path doesn't exist for example), or any other system command, the output will be displayed to STDERR causing it to display to the screen whether you like it or not, which the backticks won't capture (they will only get STDOUT). To get around this, simply add 2>&1 to the end of your command. Eg:
#!/usr/bin/ruby -w
mystring = `ls /path/does/not/exist 2>&1`;
# above will not display anything to screen but will hold error message in mystring
print mystring;
# outputs: ls: cannot access /path/does/not/exist: No such file or directory
Hope this helps.
If you have to use ls, and are using user input, you need to be paranoid:
d = IO.popen("-"){|f| if f then break f.read else system('ls', user_input) end }
This seems the be the safest way to do it, because it passed user_input to ls directly as ARGV[1], rather than sending the whole string to the shell.
With ``, the user input of /; rm -Rf ~
will result in sad faces. With the (horribly long) method above it will just result in an error.