Backticks

Wow, seems that you can use double-quoted string style substitution
for backtick system calls.

say we make a list of some files:
ls = Dir.glob(’*.doc’)
some_file = ls[2]

on OS X there is the really convenient ‘open’ tool available at the
command line for example.
open #{some_file}

Whatever application is set to default for opening .doc files will be
called to open the file.
That’s not the point as much as system calls via back ticks can be
sent variables and expressions from a Ruby script!
Very convenient!

On Fri, Aug 17, 2007, John J. wrote:

Whatever application is set to default for opening .doc files will be
called to open the file.
That’s not the point as much as system calls via back ticks can be
sent variables and expressions from a Ruby script!
Very convenient!

For added fun, try string interpolation inside regular expressions!

haystack = “foobarbaz”
needle = “bar”

haystack =~ /#{needle}/
=> 3

yeah :smiley:

whoa, can you explain a little what’s going on here? I tried it and
changed it around in irb but I can’t really figure out what’s going
on.

Simon –

Being unsure of which part is confusing you, here’s a brief run-down:

If you place a statement between backticks (the little guys above the
left tab on your keyboard) it will execute a command from the terminal
and return the output. Try ls under OSX and dir under Windows. You
can use open (osx) and start (win) to open a file with the default
application for the file type.

In a double quoted string, you can put an object between #{} to
dynamically build the string.
For example –
a = [‘Claire’, ‘Jennifer’, ‘Margaret’]
a.each {|x| puts “Hello, #{x}”}

Very neat, and you can use it in all sorts of useful things.

On 8/16/07, Simon S. r[email protected] wrote:

whoa, can you explain a little what’s going on here? I tried it and
changed it around in irb but I can’t really figure out what’s going
on.

#{} just happens to work more places than string literals:

If it helps clear it up, /#{needle}/ is roughly equivalent to

Regexp.new("#{needle}") which is sort of a silly use of interpolation,
so let’s write it as:
Regexp.new(needle)

So yeah, the string “bar” was used to construct the regexp /bar/.

On Aug 16, 2007, at 5:34 PM, John J. wrote:

Whatever application is set to default for opening .doc files will
be called to open the file.
That’s not the point as much as system calls via back ticks can be
sent variables and expressions from a Ruby script!
Very convenient!

You can do these tricks even in languages that don’t support
interpolation, as long as they allow you to set an environment variable.

James Edward G. II

ahhh, haha. well, the part that got me was it returning a “3” because
I just couldn’t find 3 instances of “bar” in there… then I realized,
f-o-o-b. 0, 1, 2, 3. :stuck_out_tongue: