I was messing around with the “system” command in Ruby!
That’s really cool, but a question immediately sprang out while using it
: I noticed that its output is a TrueClass, but how could I use the
output made of directories and files as string?
For example : if I cast a
system(‘ls’)
it will return me a variety of directories and files. So, let’s put that
I want to scan this result to find out which directories are named how
(with a Regexp), is there a way to read this output or the is solely a
TrueClass?
it will return me a variety of directories and files. So, let’s put that
I want to scan this result to find out which directories are named how
(with a Regexp), is there a way to read this output or the is solely a
TrueClass?
Related to the system method is backticks (`):
output = ls
puts “These are the directories and files:\n#{output}”
The backticks run a command similarly to the system method, but the
output of the command you give them is captured into a string and
returned. You can slice and dice the string as you please at that
point.
Keep in mind though that there are more efficient ways to handle this
particular example than using an external command to acquire a
file/directory listing.
It’s possible to skip Ruby entirely and use just the shell for many
things, and you may find that to be more efficient by some measures
depending on your needs. My comment, however, was more about avoiding
calling out to external programs when Ruby itself offers similar
functionality built-in. In this case, calling ls is needlessly
wasteful.
Whether or not you should call out to external programs for processing
of data will vary on a number of factors; including performance,
availability, cross platform compatibility, and ease of output
consumption to name a few. Be mindful of that when you start coding
calls to such programs.
It’s possible to skip Ruby entirely and use just the shell for many
things, and you may find that to be more efficient by some measures
depending on your needs. My comment, however, was more about avoiding
calling out to external programs when Ruby itself offers similar
functionality built-in. In this case, calling ls is needlessly
wasteful.
Whether or not you should call out to external programs for processing
of data will vary on a number of factors; including performance,
availability, cross platform compatibility, and ease of output
consumption to name a few. Be mindful of that when you start coding
calls to such programs.
-Jeremy
Thanks, yes of course. LS was just a trial to understand the mechanism
behind the courtain
Besides of this, try out the system option or `` to launch rails
commands while in rails console! I found it very useful!