Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Sorta? Like you're right, there's not compiled machine code that does a jump. But Ruby's case statement has nice semantics to make clear code out of what could be a complex if/elsif/else chain. The use of the === function is powerful, and lets the reader of the code focus on the condition, not the function call to check it.

    if (patternA.match(input))
    elsif (patternB.match(input))
    else
    end
vs

    case input
    when patternA
    when patternB
    else
    end
And since it uses ===, you can define that on your own classes too. Hypothetically for instance, you can make fairly complex policy type classes to make reusable boolean statements.

    case current_user
    when NotValidatedEmail
    when NotCompletedOnboarding
    when SomethingElse
    else
    end
and then you can use those elsewhere in the code by leveraging the more global use of ===

    [user1, user2].any?(NotCompletedOnboarding)


> there's not compiled machine code that does a jump

It's more of an implementation detail, but the Ruby VM actually does a jump if all the cases are "keyable"(typically integers, strings, symbols, etc). It does a hash lookup and jump to the returning address.

https://github.com/ruby/ruby/blob/92466e440d459cd21e89f8bfbe...


That's cool, thanks for the code pointer. I knew I was probably wrong in the strictest sense, especially with all the work that's gone into the various approaches to JIT and performance work in Ruby.

I should go read some of the interpreter code at some point - fun work going on there.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: