3 ms·
No mention of pattern matching being used with a case statement: https://docs.ruby-lang.org/en/3.0/syntax/pattern_matching_rdoc.html https://docs.ruby-lang.org
by werdnapk 3y ago
No mention of pattern matching being used with a case statement:
https://docs.ruby-lang.org/en/3.0/syntax/pattern_matching_rdoc.html https://docs.ruby-lang.org/en/3.0/syntax/pattern_matching_rd...
This is where some real magic happens.
- connordoner 3y agoOP has updated it off the back of this comment. https://www.akshaykhot.com/ruby-switch-statement#pattern-matching https://www.akshaykhot.com/ruby-switch-statement#pattern-mat...
- software_writer 3y agoThanks for pointing it out. I've updated it.
- Lammy 3y agoPattern matching gets even more fun with the rightward-assignment syntax and additional conditionals. Here's a single example case from the UUID/GUID library I'm working on where the constructor method takes arbitrary positional arguments, many combinations of which may yield a valid UUID. This particular case matches the components of a Microsoft-style GUID so it can handle the endianness appropriately: in [::Integer => data1, ::Integer => data2, ::Integer => data3, ::Array => data4] if ( data1.bit_length.<=(32) and data2.bit_length.<=(16) and data3.bit_length.<=(16) and ( data4.size.eql?(8) and data4.all?(&::Integer::method(:===)) and data4.max.bit_length.<=(8) ) ) then
- greenpeas 3y agoFIY, you can write `data4.all?(Integer)` because `all?` can take a pattern instead of a block, and it uses the === (just like case...when) I just learned this myself from another comment in this thread. UPD: why do you write `obj.<=(16)` instead of `obj <= 16`? is this a performance thing or a matter of style or something else?
- Lammy 3y agoJust a style thing. I find it less visually overwhelming when every statement that contributes a true/false is visually contiguous. You can see it in context here if curious: https://github.com/okeeblow/DistorteD/blob/NEW%E2%80%85SENSATION/Globe%20Glitter/lib/globeglitter.rb https://github.com/okeeblow/DistorteD/blob/NEW%E2%80%85SENSA...