4 ms·
That's because it's more like a compacted if/else ladder than what I'd traditionally think of a switch as (indexed jump). SQL has CASE...WHEN which is a simila
by userbinator 4y ago
That's because it's more like a compacted if/else ladder than what I'd traditionally think of a switch as (indexed jump).
SQL has CASE...WHEN which is a similar concept.
- cschneid 4y agoSorta? 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)
- byroot 4y ago> 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/92466e440d459cd21e89f8bfbe6d8438bcaa9389/insns.def#L1094-L1096 https://github.com/ruby/ruby/blob/92466e440d459cd21e89f8bfbe...
- cschneid 4y agoThat'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.