6 ms·
Ruby's switch statement is flexible
- cirrus3 4y agoSwift: Hold my beer
- userbinator 4y agoThat'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.
- werdnapk 4y agoNo 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 4y 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 4y agoThanks for pointing it out. I've updated it.
- Lammy 4y 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 4y 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 4y ago
- MrVitaliy 4y agoRuby is going through some kind of renascence age, I'm seeing allot of Ruby articles lately.
- connordoner 4y agoI'm personally quite enjoying it.
- imacomputertoo 4y agoI love Ruby so much. Its syntax and flexibility are such a joy to work with. I hope it does have a resurgence in popularity. I've been using it my whole career, and fearing the day I have to switch to something new.
- vlunkr 4y agoIMO Learning new languages is one of the best ways to be become a better programmer. You can carry the things you like about Ruby with you, and learn to think about things in new ways.
- baremetal 4y agoLoving all the Ruby articles. Ruby has been my favorite language ever since i discovered it back in 08. Before that I was using Perl..
- brightball 4y agoProductivity is a very sticky feature. IMO there's no language that I know of which effectively competes with Ruby in this category. I don't even know if people realize that Ruby is the closest thing to an Aspect Oriented Programming experience in the wild, at least that I've seen. It's the secret sauce IMO.
- SkyPuncher 4y agoI feel like people got hung up on computational performance for a while. 5 to 10 years ago, a bunch of big startups hit the scale where they needed to intentionally work around Ruby's limitations. People seemed fixate on those performance issues while overlooking the business context - that hitting that scale means you are wildly successful and solving problems most startups never have the chance to solve. It seems there's a swing back towards people considering raw productivity. Especially, at early stage or pre-product market fit. Given that Rails is highly correlated with Ruby usage, it's simply hard to beat how much productivity and breadth that Rails gives you. Especially, with how much "grunt" work is easily handled by it. I love trying new frameworks on side projects, but I always find myself coming back to Rails. There is inevitably some nuanced situation that the framework doesn't handle that would be ridiculously easy in Rails.
- web3-is-a-scam 4y agoRuby is a wonderful language, I just wish I wasn't stuck with 2.6 at work because all of the improvements especially in Ruby 3.0 are just wonderful. I keep wanting to branch out to other languages but keep coming back to Ruby as my bread and butter.
- werdnapk 4y agoYou really need to push to upgrade to 3.0. Ruby 2.6 and 2.7 have passed EOL and are no longer being supported.
- web3-is-a-scam 4y agoBelieve me, I know. But management doesn't give a crap about that. We're still on Postgres 10 as well as Redis 5. Send help.
- rakoo 4y ago1. Ask management to write in full letters and sign a paper basically saying "I acknowledge that not maintaining software up-to-date is a security risk and opens the company to substantial financial damage" 2. Hire a Pwn-As-A-Service to extract data from your company from the outside 3. Tell management "I told you so" You didn't read this here More seriously, I think the best you can do is not expect to find happiness in a setting that you don't fully control (ie your job), accept that, and look for joy elsewhere. It might be another job, it might be another hobby. Work fewer hours.
- izietto 4y ago> More seriously, I think the best you can do is not expect to find happiness in a setting that you don't fully control (ie your job), accept that, and look for joy elsewhere. It might be another job, it might be another hobby. Work fewer hours. That's how I upgraded from Ruby 2.4 / Rails 5.0 to Ruby 3.2 / Rails 7.0
- web3-is-a-scam 4y ago
- deleted 4y ago[deleted]
- formerly_proven 4y agoAm I too dumb to find it or do the Ruby docs not contain a description of the language? https://ruby-doc.org/3.2.2/ https://ruby-doc.org/3.2.2/ only seems to contain API docs.
- deleted 4y ago[deleted]
- irishsultan 4y agoYou need to take a closer look at the Pages sidebard, there is for example this https://ruby-doc.org/3.2.2/syntax/pattern_matching_rdoc.html https://ruby-doc.org/3.2.2/syntax/pattern_matching_rdoc.html
- nanny 4y agoThat's the Core reference guide. You might want the book "Programming Ruby"[1], which is linked on the documentation landing page[2]. Alternatively, for a quick overview, I recommend Learn X in Y Minutes[3]. [1]: http://ruby-doc.com/docs/ProgrammingRuby/ http://ruby-doc.com/docs/ProgrammingRuby/ [2]: https://www.ruby-lang.org/en/documentation/ https://www.ruby-lang.org/en/documentation/ [3]: https://learnxinyminutes.com/docs/ruby/ https://learnxinyminutes.com/docs/ruby/
- stonemetal12 4y agoFrom [1] > This book documents Version 1.6 of Ruby Has nothing about the language changed since 1.6?
- fknorangesite 4y agoHah yeah, uh, make sure you get a more recent edition that was published less than 20 years ago. A profound amount has changed since then. Looks like the 5th edition covers v3.2.
- stonemetal12 4y agoDid you expect something else? The way I get to that link is to go to ruby-doc.org and click on "Complete API docs for Ruby 3.2.2". API docs is what I expected.
- mock-possum 4y agoWhoa 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
- pizza234 4y agoSmall mistake on the `/\D/`: the correct semantic is "the string (or any matchable class) includes a character that is not a number". It will also never match a number, although it's kinda ok because it's supposed to be an example of the functionality.
- ajdude 4y agoVery similar to Ada'a switch statement, which utilities "case .. when". I don't think Ada can utilize regex in their switch statements but they can do neat things like convert a string into its corresponding enumeration.
- cout 4y agoRuby does not have a switch statement; it has a case expression (which can be used in a statement).
- ape4 4y agoThat naming is rather maddening.
- layer8 4y agoIt’s the same in SQL and Ada. “Case” is an abbreviation for “case distinction” here. “Switch” was never intuitive to me, because nothing gets switched.
- mekster 4y ago"Switch" to this statement in "case" of this expression, seems quite easy to grasp.
- calo_star 4y agoIt's the same in Haskell, Erlang and Elixir.
- nomilk 4y agoTangental, but this article deserves huge credit for having code containing the main point right at the top allowing the reader to derive the main point in < 20 seconds. I wish more written content was like this. Brilliant.
- adverbly 4y agoIt's cool that Ruby has a === operator, but the fact that it is not a more strict version of == has caused me trouble in the past. In TypeScript === is more strict, and when I go back and forth between Ruby and TS I have made a mistake in the past by putting a === when I intended a strict equality check. I wonder if there is a linting setting where you can prevent your code base from ever using it.
- nusaru 4y agoHere you go: https://docs.rubocop.org/rubocop/cops_style.html#stylecaseequality https://docs.rubocop.org/rubocop/cops_style.html#stylecaseeq...
- deleted 4y ago[deleted]
- djur 4y ago`rescue` also uses the match operator, which I found useful in the past when wrapping libraries that didn't expose a useful exception type hierarchy. In particular I seem to recall that the "pg" gem would throw `PG::Error`, with the actual error details from the Postgres server only accessible in the `message`. I wrote a little library that allowed me to create "virtual" exception types that could match based on the message or the result of an arbitrary proc (if the underlying exception class offered a `code` or `reason` attribute, for instance). For all its (sometimes deserved) reputation as a big and complex language, Ruby is actually pretty good at making sure that language features are made with the same underlying building blocks, and thus two things that look similar probably work similarly as well.
- caseyohara 4y agoWow I've been programming Ruby for 15 years and didn't know `rescue` uses a match operator. It's annoying when a library raises only one exception type for every error and the only difference is in the message. Matching on the message right in the rescue expression would be tremendously useful instead of parsing the message and deciding how to deal with it inside the rescue body.
- djur 4y agoHere's the library: https://github.com/mboeh/toe_tag https://github.com/mboeh/toe_tag It's a decade old and less than 100 lines so it might be more useful as an example than a gem. The last time I needed to do something like this I just rewrote the parts I needed. The ecosystem is just generally better about exceptions than it used to be, too.
- veidelis 4y agoThis made me laugh: def can_drive(age) case age when 1..14 then 'no' when 15..100 then 'yes' end end puts can_drive(18) # yes I haven't used Ruby for a long time, and I don't feel bad about it.
- tabtab 4y agoThe "C" family has one of the worst case/switch statements out there. When Java et. al. cloned it, they should have provided an alternative. Perhaps keep the old style for backward compatibility, but provide a new one with different key-words to avoid confusion. Example: select(a) { when 1,2,3 {...} when 4 {...} when 5,6 {...} otherwise {...} }
- twic 4y agoAgreed that the C-style switch is crammed with misfeatures. But Java does now let you write this (haven't tried compiling this, may contain small errors): static String describe(int change) { return switch (change) { case 0 -> "unchanged"; case -1, 1 -> "mostly unchanged"; case Integer i && i > 0 -> "increased"; case Integer i -> "decreased"; } } No fallthrough, can mix constants and conditions (with syntax some will find clunky), and is an expression.
- hk1337 4y agoeven = ->(x) { x % 2 == 0 } even === 4 # true even === 5 # false That's cool. No need for a is_even or is_odd gem. I really do like that ability to do a case statement though. I cannot think of a situation where I need it now but I could definitely see it being handy instead of having to do if..else if
- chao- 4y agoAlternatively you can call Integer#even? or Integer#odd? directly: 4.even? # true 5.even? # false Or if you really want to use ===, it is possible with the slightly sillier (imho) use of Symbol#to_proc: case some_num when :zero?.to_proc then "zero" when :even?.to_proc then "even" when :odd?.to_proc then "odd" end I say sillier, because even though it is very explicit, the use of #to_proc, by name, feels just a tiny bit less awesome than its usual use via the & operator, e.g. array_of_nums.map(&:odd?). It would be really cool to be able to write: case some_num when &:zero? then "zero" when &:even? then "even" when &:odd? then "odd" end However I say this with no grasp of just how complex that could be to implement, or other implications for the language's grammar.