Search code examples
stringjrubyembedded-language

What characters can I use to quote this ruby string?


I'm embedding JRuby in Java, because I need to call some Ruby methods with Java strings as arguments. The thing is, I'm calling the methods like this:


String text = ""; // this can span over multiple lines, and will contain ruby code
Ruby ruby = Ruby.newInstance();
RubyRuntimeAdapter adapter = JavaEmbedUtils.newRuntimeAdapter();
String rubyCode = "require \"myscript\"\n" +
                            "str = build_string(%q~"+text+"~)\n"+
                            "str";
IRubyObject object = adapter.eval(ruby, codeFormat);

The thing is, I don't know what strings I can use as delimiters, because if the ruby code I'm sending to build_string will contain ruby code. Right know I'm using ~,but I think this could break my code. What characters can I use as delimiters to make sure my code will work no matter what the ruby code is?


Solution

  • use the heredoc format:

    "require \"myscript\"\n" +
              "str = build_string(<<'THISSHOUDLNTBE'\n" + text + "\nTHISSHOULDNTBE\n)\n"+
              "str";
    

    this however assumes you won't have "THISSHOULDNTBE" on a separate line in the input.