简体   繁体   中英

Why does my global variable given by JRuby to my ruby script empty?

My Ruby script:

def start
    print "Global variable: #{$globalVariable}"
end

Java code executing it:

    jruby = new ScriptEngineManager().getEngineByName("jruby"); // Create engine
    jruby.eval(myRubyScriptContents);   // Evaluate my ruby script
    jruby.put("$globalVariable", this);  // Give it a global variable
    Invocable invocable = (Invocable) jruby;
    invocable.invokeFunction("start");    // Call the start method to print my variable

Output is this:

Global variable:

Why is my variable empty?

It would be helpful if you could provide a working example of your problem when posting.

Here is a working solution (note absense of dollar sign in engine put ).

import javax.script.*;
class TesterApp {
    public static void main(String[] args) throws Exception {
        ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
        jruby.eval("def start;print \"Global variable: #{$globalVariable}\";end");
        jruby.put("globalVariable", "This is a working example.");
        Invocable invocable = (Invocable) jruby;
        invocable.invokeFunction("start"); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM