ルビーの練習 - メソッド 2008/09/04

JRubyです。


いまいちクロージャーとブロックとメソッドの仕組みがわかってないです。

とりあえず、メソッドで実験。
メソッドをハッシュに格納してとりだして利用するって感じのことがしたいのでした。
callを使うといいようです。callを使わないでも実行できないのかしら。

サンプル
#
def hello( name )
p "hello, " + name
end

hello "ugo!!"

hello_m = method :hello
(method :hello).call "ugo"
hello_m.call "o_o!"
hello("-_-!")
n = {"hello" => hello_m , "hey" => :hello }
p hello_m
n['hello'].call("OKo_o!")
p n['hey']


結果
"hello, ugo!!"
"hello, ugo"
"hello, o_o!"
"hello, -_-!"
#<Method: Object#hello>
"hello, OKo_o!"
:hello



Javaコード
package test_jruby;

import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.bsf.util.IOUtils;
import org.jruby.Ruby;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.GlobalVariable;
import org.jruby.runtime.builtin.IRubyObject;

public class Test_Executor {

public static void main(String[] args) throws IOException {

final Ruby ruby = Ruby.newInstance();
final String script = script("test_method.jruby", "MS932");
evalByJRuby_GLV(ruby, script, new Object[][] {});

}

static public String script(String filename, String enc) throws IOException {
String script = IOUtils.getStringFromReader(new InputStreamReader(
ExperimentationJRubyScriptBase.class
.getResourceAsStream(filename), enc));
return script;
}

/**
* <p>
* Rubyスクリプトにグローバル変数で値を渡します。
* </p>
*
* @param ruby
* @param script
* @param objects
* @return
*/
public static String evalByJRuby_GLV(Ruby ruby, String script,
Object[][] objects) {

synchronized (ruby) {

if (objects != null) {
for (int i = 0; i < objects.length; i++) {
Object[] objects2 = objects[i];
if (2 <= objects2.length) {

ruby.defineVariable(new GlobalVariable(ruby, "$"
+ objects2[0].toString(), JavaEmbedUtils
.javaToRuby(ruby, objects2[1])));
}
}

}
IRubyObject result = ruby.evalScriptlet(script);
ruby.tearDown();
if (result instanceof org.jruby.RubyString) {
org.jruby.RubyString s = (org.jruby.RubyString) result;
return s.getUnicodeValue();
}
return result.toString();

}

}
}

: