Is there a way to translate C code into Ruby?

I am sitting with a huge amount of legacy C code that needs to be converted to Ruby for a project.

I saw Ruby to C translators online, but not vice versa. Will there be an easy way to approach this particular problem?

+4
source share
5 answers

You will need to write a C translator in Ruby, which is possible, but this may not be justified, or you can break the C code into smaller modules, which you can create Ruby wrappers as a first step. Once they are all wrapped in Ruby, and the main control flow is executed in Ruby, you can write a test harness (both to verify the replacement code and support reverse engineering) and start replacing C modules with Ruby modules.

The split and subjugation approach should work with regular Ruby if you use modules as your own extensions, but obviously this will cause additional problems if you configure something like JRuby as a runtime. If you want to do something similar in JRuby according to your comment, you are looking at packing the C modules in the JNI and calling from the JVM in this way. In any case, your C code will interact with Ruby code, but both approaches are not interchangeable.

None of the approaches will be quick, and both will work hard.

+6
source

You can:

  • Write a C interpreter in Ruby (very complicated).
  • Wrap the compiled C code with something like SWIG (much simpler).
+1
source

At the very least, it is possible to translate a subset of C into Ruby, but the output will be an "erased" program.

Using a generic transporter , you can convert this C function to Ruby:

int add(int a,int b){ return a+b; } 

This is the translator output:

 def add(a,b) return a+b end 
+1
source

C programming and Ruby programming have completely different programming paradigms. Thus, although the old adage that you can write Fortran code (or C in this case) in any language is true, the Ruby code that you end up with machine translation will not be Ruby at all, except syntactically.

So, IMHO, otherwise than a guide (and made by experienced rubists, I could add) would be either impossible, or at least not useful at all.

0
source

Maybe you can try this https://github.com/jackieju/CPP2Ruby/ It is fresh for cpp, but lasted longer from c to ruby

0
source

Source: https://habr.com/ru/post/1305833/


All Articles