From: Brian Candler Date: 2008-10-28T06:12:38+09:00 Subject: Re: automatic code conversion from Ruby to C ? Axel Etzold wrote: > I am looking for a (semi-)automatic conversion of a Ruby script to C or > C++, so > that readable source code for a human C/C++ programmer is produced. > > The program should read in text from a file as a string, split and > search it using regular expressions, > convert some numbers into floats and perform some calculations on them > (the latter part is done using some existing C code). It sounds like you think that you can use Ruby as a shorthand way of writing C. Unfortunately it doesn't work that way. Bear in mind that the biggest pain with C is to do with memory allocation. Ruby has a whole run-time environment for creating and manipulating Ruby objects. So this mechanically-generated C code would just be calling Ruby libraries to create objects or dispatch methods. So in that case, why not just write it in Ruby and run it? The other part you say is that you want to interact with existing C code. This may be easier than you think. A good starting point is http://www.ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html Look also at the RubyInline gem, which lets you write C directly inside your Ruby (yes!) > Is there some gem that would ... translate it for > me into > readable C/C++, such that I'd have to specify as few as possible size > and variable > type declarations ? If it did, it would just be VALUE foo; VALUE bar; VALUE baz; /* VALUE is a reference to a Ruby object, whether it be an Array, a String, or an integer */ > and I'd have a hard time defending the use of a scripting language with > the people > I am collaborating here. Prototype it in Ruby. If it works fast enough, then you've saved yourself a lot of work. Even if it's too slow, you'll have a more concrete idea what you're trying to do and how to achieve it. Reading 100,000 lines in Ruby doesn't take very long. Another option would be to write a Ruby script to "normalise" your input into a format which is easier for your C program to read. For example, it could output point1 point2 distance tuples. This would probably be sufficient: src_point = nil while line = $stdin.gets line.chomp! if line =~ /^-/ src_point = nil elsif src_point.nil? src_point = line elsif line =~ /^(\S+)\s*(\d+)$/ puts "#{src_point} #{$1} #{$2}" else STDERR.puts "Invalid line: #{line.inspect}" end end Output: P1 P2 23 P1 P4 27 P2 P3 1 P2 P5 457 P2 P6 3 P2 P377 56 Your C program would still need to build a graph data structure from this though. There are probably existing C libraries to work on data sets like this, if you hunt hard enough. -- Posted via http://www.ruby-forum.com/.