Home > Back-end >  Ruby: How to escape backslash (`\`) to generate a command in ruby?
Ruby: How to escape backslash (`\`) to generate a command in ruby?

Time:10-24

I have a hash in ruby like below:

{"metric"=>"Mean F-Score",
 "columns"=>
  [{"name"=>"Id",
    "type"=>"String"},
   {"name"=>"Expected",
    "type"=>"String"}],
 "files"=>
  {"expected"=>"actual_output.csv"},
 "submission_filename"=>"/a/aa/submission.csv"}

The json for this hash is

irb(main):101:0> json_string = JSON.generate(a)
=> "{\"metric\":\"Mean F-Score\",\"columns\":[{\"name\":\"Id\",\"type\":\"String\"},{\"name\":\"Expected\",\"type\":\"String\"}],\"files\":{\"expected\":\"actual_output.csv\"},\"submission_filename\":\"/a/aa/submission.csv\"}"

I want to generate a bash command which can generate a json file using this json string:

I tried

irb(main):104:0> "echo \"#{json_string}\" > data.json"
=> "echo \"{\"metric\":\"Mean F-Score\",\"columns\":[{\"name\":\"Id\",\"type\":\"String\"},{\"name\":\"Expected\",\"type\":\"String\"}],\"files\":{\"expected\":\"actual_output.csv\"},\"submission_filename\":\"/a/aa/submission.csv\"}\" > data.json"

But on running this command on bash it is generating wrong json file.

I am trying to learn ruby and want to generate command (to run on different servers) like this, but was unable to escape the backslash:

echo "{\"metric\":\"Mean F-Score\",\"columns\":[{\"name\":\"Id\",\"type\":\"String\"},{\"name\":\"Expected\",\"type\":\"String\"}],\"files\":{\"expected\":\"actual_output.csv\"},\"submission_filename\":\"/a/aa/submission.csv\"}" > data.json

CodePudding user response:

You need to do 2 things to make this work

  1. Wrap the echo parameters in single quotes to include double quotes in the output.
  2. Use some ruby method to print the string to console like puts or print (otherwise ruby will print a string to the console with double quotes escaped like \")
puts "echo '#{json_string}' > data.json"

This should output something like the below which you can run on the terminal to generate a JSON file.

echo '{"metric":"Mean F-Score","columns":[{"name":"Id","type":"String"},{"name":"Expected","type":"String"}],"files":{"expected":"actual_output.csv"},"submission_filename":"/a/aa/submission.csv"}' > data.json
 => nil

CodePudding user response:

Did you try:

`echo "#{json_string}" > data.json`

This executes a shell command from your irb-console. Found in https://ruby-doc.org/core-3.1.2/Kernel.html#method-i-60

  • Related