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

GitHub: https://github.com/dickensas/kotlin-gradle-templates/tree/master/embed-ruby

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)
}

MSYS2 : https://www.msys2.org/

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

For Python use this code embed python in kotlin

For Lua use this code embed lua in kotlin

For R use this code embed R in kotlin

For TCL use this code embed tcl in kotlin

 

Add new comment