RubyからGroovyの標準入力に渡して処理させて出力を読む

発端:

こういうのは JRuby 使った方がいいのかもしれません(使ったことがないので分かりませんが…)。

とりあえず結果:

Ruby(foo.rb):

# -*- coding: utf-8 -*-

def proc_by_groovy(groovy_script, str)
  IO.popen(%Q{groovy "#{groovy_script}"}, "r+"){|io|
    io.print str
    io.close_write
    io.read
  }
end

p proc_by_groovy("bar.groovy", "foo\\nあ\n")
#=> "foo\\nあ\n_bar"

Groovy(bar.groovy):

def readStdin() {
  def reader = new InputStreamReader(System.in)
  def builder = new StringBuilder()
  char[] buf = new char[1024]
  int numRead
  while (0 <= (numRead = reader.read(buf))) {
    builder.append(buf, 0, numRead)
  }
  builder.toString()
}

def src = readStdin()
print src + "_bar"

readLine() すると改行が取れないせいで思ったよりめんどくさかったです。

readStdin の部分はほぼ Re: InputStreamからStringへの変換 - 永遠に未完成 の丸写しです。



bar.groovy は Ruby だったらこうですね

src = $stdin.read
print src + "_bar"