Backquotes

One other type of string deserves a special mention: a string enclosed by backquotes—that is, the inward-pointing quote character that is usually tucked away up toward the top-left corner of the keyboard: `.

Ruby considers anything enclosed by back-quotes to be a command that can be passed for execution by the operating system using a method such as print or puts. By now, you will probably already have guessed that Ruby provides more than one way of doing this. It turns out %x/some command/ has the same effect as `somecommand` and so does %x{some command}. On the Windows operating system, for example, each of the three lines shown next would pass the command dir to the operating system, causing a directory listing to be displayed:

4backquotes.rb

puts(`dir`)
puts(%x/dir/)
puts(%x{dir})

You can also embed commands inside double-quoted strings like this:

print( "Goodbye #{%x{calc}}" )

Be careful if you do this. The command itself is evaluated first. Your Ruby program then waits until the process that starts has terminated. In the present case, the calculator will pop up. You are now free to do some calculations, if you want. Only when you close the calculator will the string “Goodbye” be displayed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.198