2.5 Ways to Execute a Shell Command

I always get confused by the difference between %x{}, backticks, and system "command", so I wrote down what the difference was. %x{} is actually the exact same thing as backticks, but it’s useful because you can nest backticks inside it.

system "command" echoes to STDOUT, and returns true if the command succeeded.

irb > system "echo ABC"
ABC
 => true 

Backticks and %x{ } do not echo to STDOUT, and return the result of running the command.

irb > `echo ABC`
 => "ABC\n" 
irb > %x{echo ABC}
 => "ABC\n"
irb > %x{echo `which ruby`}
 => "/Users/gabe/.rvm/rubies/ruby-1.9.2-p290/bin/ruby\n"

Sharpen your programming skills by completing coding exercises that are reviewed by other developers at Upcase today.