Unfortunately, there isn’t yet a migration tool from Ruby to Crystal, but converting Ruby code to Crystal is often quite straightforward. Consider the following:
A lot of the dynamic power of Ruby does not exist in Crystal. This includes eval, send, instance_eval, auto_load, and define_method. Macros in Crystal can sometimes be used to achieve the same goal.
Crystal also has less introspection—for example, methods doesn’t exist on an object, though @type.methods works in macros.
When overflow occurs in integer calculations, Ruby converts automatically from Fixnum to Bignum. Crystal 0.27, on the other hand, applies simple modular arithmetic. (Overflow is planned to appear in future versions of Crystal, however.)
The following table can help you to quickly convert Ruby code to Crystal:
From Ruby | To Crystal |
---|---|
NilClass | Nil |
TrueClass, FalseClass | Bool |
Fixnum | Int8, Int16, Int32, Int64, or same with U prefix |
and | && |
or | || |
Strings: " " or ’ ’ | only " " |
” | "" |
’"cute"’ | ""cute"" or %{"cute"} or %("cute") |
Heredoc: STR =<<DOC_NAME | STR = <<-DOC_NAME |
for in | .each |
trailing while or until | no equivalent, trailing if or unless |
[] | [] of Type |
{} | {} of KeyType => ValueType |
$ | $~.pre_match |
$‘ | $~.post_match |
&: | &. |
attr_reader | getter |
attr_writer | setter |
attr_accessor | property |
length, size, count | size |
Enumerable#detect | Enumerable#find |
Enumerable#collect | Enumerable#map |
Enumerable#find_all | Enumerable#select (or grep if a regex pattern) |
Enumerable#inject | Enumerable#reduce |
fail | raise |
File::exists? | File.exists? |
File.readlines | File.read_lines |
Hash.each_pair | Hash.each |
include? | includes? |
Kernel#proc | -> |
Kernel#lambda, Proc#new | -> |
lambda { |x|... } | ->(x: Type) { ... } |
Object#respond_to? | Object#responds_to? |
require_relative "abc" | require "./abc" |
class << self | def self.abc |
private | private def |
STDOUT.write | STDOUT.print |
YAML.load | YAML.parse |
"open-uri" open.readlines | "http/client" get(..).body.lines |
Here[146] is a shard written by Faustino Aquilar to evaluate and assist in the porting of Ruby gems to Crystal.
52.15.38.176