2

Below is the code i am using to Convert from RubyString to Java Char.. Could you please suggest me better way where Jruby (automatically handles these kind of Type Error or some code in jruby to convert)

ruby_string="Raj"

java.lang.String.new(col_value)
col_value=str_obj.charAt(0)
2
  • Are you just trying to get the first character of ruby_string? And what's the broader purpose of what you're trying to do? Commented Oct 22, 2012 at 21:16
  • No.. i was trying to convert above ruby_string(ruby_string) to Java Character to call java method which accepts java char as argument Commented Oct 25, 2012 at 7:22

1 Answer 1

7

First, JRuby behaves a little differently depending on whether you run it in 1.8 mode or 1.9 mode. With JRuby 1.7.0 and up, 1.9 is the default; with others, 1.8 is the default. To change the default, you pass either --1.8 or --1.9 to jruby on the command line.

In 1.8 mode, certain operations on strings, like getting the character at a single index, return numbers (Fixnums), whereas in 1.9 mode they always return strings. JRuby converts automatically between Ruby Fixnums between 0 and 65535 and Java chars, so you can pass a 1.8-mode "character" value directly to a Java method that accepts a character; e.g.

str = 'foo'
java_obj.methodThatTakesAChar(str[0])

In 1.9 mode, since str[0] is a single-character string, you have to convert its character to a number. You do this with the ord instance method:

str = 'foo'
java_obj.methodThatTakesAChar(str[0].ord)

I hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.