tags:

views:

506

answers:

3

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

+3  A: 

The backtick executes a system command and returns it output as a string.

result = `ls ~/Downloads`

puts result.reverse
puts result.split('/')
Squeegy
+1 That is sweet. Learn something new everyday. :) I used system all the time without knowing the output was returned as a string.
Beanish
Every method in Ruby returns something. Granted, sometimes that something is `nil`, but more often than not that return is exactly what you expect it might be. Just fire up `irb` and try it. If it prints output, then it returned something.
Squeegy
+4  A: 

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.

So formal to be using semi-colons!
tadman
It's a habit I haven't been able to kick yet unfortunately;
I love semicolons.
Alex JL
Wait what? Semicolons are okay in Ruby!? Excellent, that was something I was worried would get in my way when I finally sat down to try to learn it. Now I have... a crutch I can use, and thus not kick the habit for a while, like insertable. Wait, is that really a good thing?
Platinum Azure
Thanks insertable!
lbburdick
Semicolons are actually significant as well. They almost always mean the same thing as a newline would. Try `(1..18000).to_a` vs `(1..18000).to_a; 4` and `a=3; if a==4; a+2; else a+5 end` in irb. Note that that doesn't necessarily mean these are good things to do in a real program. ;) But they are occasionally useful when declaring quiet classes: `class Explosion < StandardError; end`, and such.
Tim Snowhite
+2  A: 

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.

cwninja
Pair or quote your initial backtick in the last sentence to fix the syntax highlighting for your comment.
Myrddin Emrys