Sometimes when I’m trying to compare the languages, particularly for new features or changes, I’ll write a script that should work in both languages. However, sometimes I need a conditional that says “If run from Ruby do X, else if run from Crystal do Y”. Is there something in the language that can help me with this?
I instinctively reached for $0, but that seems to have been removed from the language in favor of ::PROGRAM_NAME, but then of course ::PROGRAM_NAME doesn’t exist in Ruby.
One thing to consider would be to reach out to the Ruby core devs and see if both communities could unify around a single constant to check, to avoid having to use dirty hacks.
Maybe… but I don’t see much serious use for this anyway. While Crystal and Ruby are close, there are enough differences in syntax and semantics that it’ll be hard to write any meaningful polyglot program.
If it’s only about showing off neat tricks, dirty hacks should be just fine.
Yeah, as soon as you get even slightly complicated the comparisons break down. In my case I learned something new[1] in Crystal, and was curious what Ruby did as a comparison to help drive the language changes being proposed, as I personally like when the languages stay consistent with each other.
Margret’s idea to have a .rb and a .cr require could help:
# language.rb
def is_ruby(&); yield; end
def is_crystal(&); end
# language.cr
def is_ruby(&); end
def is_crystal(&); yield; end
# example.crb
require "language"
is_ruby { do_something } # <= crystal skips the block
is_crystal { do_something_else }
Granted, whatever’s in each block must be parseable by both language. Crystal will skip the is_ruby blocks, but it will still be parsed and must ve valid Crystal, then Ruby needs to parse the is_crystal block and so it must be valid Ruby too.