General
Some tricks that work in Ruby also work in Crystal. Some don't. Crystal has some tricks of its own, of course!
Iteration
(0..9).map{} # returns an array
10.times{} # returns nil
0.to 9{} # also returns nil, but very short. always better than the previous line
("0".."9").map{} # could occasionally be useful
String manipulation
- Crystal's string
gsub
method can do more than Ruby's. You can call it with just a block, and the block doesn't have to return a string.
"123abcABC".gsub{|c|c.ord} # "495051979899656667"
- Sadly, Crystal doesn't have Ruby's
*
overload for joining arrays of strings. But, Crystal's array join
method can take a block and transform each item before joining.
[1, 2, 3].join{|x| 2*x} # "246"
eval
- If you find yourself missing Ruby's
eval
, rejoice: Crystal has eval too! You can write in a command literal,
`crystal eval "#{your code string here}"`
to eval your troubles away. Will that ever be good for golf? I don't know. If you want to use eval, you might want to use macros instead?