Call Ruby from Kotlin or embed Ruby code inside Kotlin

Submitted by Dickens A S on Fri, 11/22/2019 - 15:36

Embedded Ruby inside Kotlin

Compile and Execute from MSYS2 or Cygwin with ruby development C header files

Demo output

Embed Ruby

Ruby code which is running inside Kotlin

#!/mingw64/bin/ruby
# I'm a ruby script!
print "Hello, world! - ruby\n"
def testfun(a)
   puts "The first parameter from kotlin is #{a}\n"
end

Kotlin Code which has embedded ruby code in string

package plot

import ruby.*
import kotlinx.cinterop.*

var rubyscript =
"""
#!/mingw64/bin/ruby
# I'm a ruby script!
print "Hello, world! - ruby\n"
def testfun(a)
   puts "The first parameter from kotlin is #{a}\n"
end
"""

fun main() {
    ruby_init()
    rb_eval_string(rubyscript)
    rb_funcall(Qnil, rb_intern("testfun"), 1, rb_str_new_cstr("dickens"))
    ruby_cleanup(0)
}

Install MSYS2

This is required for windows to download pre-compiled libraries and its headers

pacman -S mingw-w64-x86_64-ruby 

change x86_64 to i686 for 32 bit widows

Source Code

End Of Article

Add new comment