News for hackers. Stuff that matters.
Re:An Ode to Ruby by brigandish on Monday January 10, 2022 @10:04PM (#29886862)
> I think I'd be more interested in Crystal if it was easier to integrate into existing ruby code bases via something like the FFI.

That would be very nice, I agree, though I've always found the FFI interface an under-documented pain so I'd probably end up just using Crystal or using some other way to interoperate, like pipes or HTTP.

On Sorbet, I just hate the look of it. I know it's subjective (possibly that's Ruby's own fault for being so delightful to look at, I'm spoiled!) but I can't abide the syntax. Crystal's is much nicer, and has some extra sugar sprinkled on top for the moments you're most likely to be using it (like external names in method signatures[1] or providing init args) that win out for me.

Sorry about the formatting, I can't work out HN's markdown :/

  # Ruby

  # from the Sorbet intro
  extend T::Sig

  sig {params(name: String).returns(Integer)}
  def main(name)
   puts "Hello, #{name}!"
   name.length
  end


  # Crystal

  def main(name : String) : Int
   puts "Hello, #{name}!"
   name.size
  end

  puts main "you"

That's so much nicer to my eyes, and you don't need most of it as it will be inferred.

Initialisation is nicer, too, (unless Ruby has been updated in this regard too? As I wrote, I use it much less now)

  # Crystal

  class A
   getter name : String
   def initialize(*, @name); end
  end

  a = A.new name: "Hacker News"
  puts a.name
or without the getter and keyword arg:

  # Crystal

  class A
   getter name 
   def initialize(@name : String); end
  end

  a = A.new "Hacker News"
  puts a.name
Whatever suits.

  # Crystal

  # Example of external names

  def increment(value, by)
   # OK, but reads odd
   value + by
  end

  def increment(value : Int, by amount : Int) : Int
   # Better
   value + amount
  end

  puts increment 1, 2

but those types are easily inferred so it's actually:

  # Crystal

  def increment(value, by amount)
   # Even better
   value + amount
  end

I could go on because now I'm comfortable with it, it looks much better. I feel the way moving from Perl and C# to Ruby felt.

[1] https://crystal-lang.org/reference/1.3/syntax_and_semantics/...

Edit: formatting, of course

There are no comments on this comment yet.