How to call shell commands from Ruby

前端 未结 20 2363
旧时难觅i
旧时难觅i 2020-11-22 01:10

How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

20条回答
  •  情话喂你
    2020-11-22 01:53

    The way I like to do this is using the %x literal, which makes it easy (and readable!) to use quotes in a command, like so:

    directorylist = %x[find . -name '*test.rb' | sort]
    

    Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:

    directorylist.each do |filename|
      filename.chomp!
      # work with file
    end
    

提交回复
热议问题