3 ms·
Whoa that’s wild. > Note: There're no break statements at the end of each when clause. Unlike other languages, Ruby's case doesn't fall through. Aw no fall th
by mock-possum 4y ago
Whoa that’s wild.
> Note: There're no break statements at the end of each when clause. Unlike other languages, Ruby's case doesn't fall through.
Aw no fall through?
> Note: Do not use obj.class in the case clause, as Integer === Integer returns false.
Wait what
- TRiG_Ireland 4y agoThis seems to work instead of fall through, though: when 60, 70
- vidarh 4y ago> Wait what `Integer ===` (and more generally if `===` is implemented as a class method) checks if the right hand side is of the class Integer. The object Integer is not, it's an object of class Class. EDIT: In other words: $ pry [1] pry(main)> Integer === Integer => false [2] pry(main)> Class === Integer => true [3] pry(main)> Integer.class => Class
- marcosdumay 4y ago> Aw no fall through? That's a good thing. In fact, that's the only thing on the article that is unambiguously good. Fall through only serves to create bugs.
- mock-possum 4y agonaw, fallthrough is fun, and helps you be explicit about handling cases without repeating yourself.
- hnuser847 4y agoThe switch statement in Ruby uses the `===` method under the hood. `===` does not mean "equals" like it does in Javascript. Instead, `a === b` means, does `b` belong in the set of `a`. irb(main):001:0> Integer === Integer => false irb(main):002:0> String === String => false irb(main):003:0> Object === Integer => true irb(main):004:0> Object === String => true
- radiospiel 4y agoThis might confuse a reader. The Object === cases are successful, because the Class-objects Integer and String are Objects. In ruby everything is an Object.
- hnuser847 4y agoThat's a good point. This might be a better example: irb(main):009:0> String === String => false irb(main):010:0> Integer === Integer => false irb(main):011:0> Class === Integer => true irb(main):012:0> Class === String => true
- LanceH 4y agoThis makes more sense and seems less egregious when you look at it in use, in a case: a = [] case a when Array puts true else puts false end
- burke 4y agoYeah: it's almost more true to say that `a === b` just means whatever we've decided `case b when a` should check. `===` is almost never used directly.
- deleted 4y ago[deleted]
- greenpeas 4y ago> Wait what Ruby's triple equals (`===`) is defined differently based on the type of the operand on the left hand side. `a === b` is syntactic sugar for `a.===(b)`; and for classes `klass.===(other)` is defined as `other.is_a?(klass)`. More examples here: https://dev.to/baweaver/understanding-ruby-triple-equals-2p9c https://dev.to/baweaver/understanding-ruby-triple-equals-2p9...