11 ms·
"Useless Ruby sugar": Argument forwarding
- kunley 3y agoThe author goes deep in explaining not only the technical details, but also the motivation why things were crafted in a certain way. Actually all of his articles on Ruby are like that, personally I like it a lot
- fijiaarone 3y agoI’ll take “how to make code slower and more error prone in order to save a few keystrokes at the cost of readability” please.
- michaelcampbell 3y agoReadability is a function of the reader, not the code. It's a dog-whistle that just means "familiarity".
- fijiaarone 3y agoReally, it’s because of the habit of Ruby programs to pass a single options (params, args, config) object in to avoid complex configuration. Really, what’s needed is separation of concerns, instead of a single “do stuff” function that takes an “everything” argument. But what’s really wanted is global variables with everything is a single scope.
- bluecheese452 3y agoRuby in a nutshell.
- andrei_says_ 3y agoThat’s certainly a valid perspective. Another one, “how can we make a powerfully expressive programming language feel malleable, accommodating and pleasant in the hands of experienced devs?” I equally valid. As someone who writes Ruby I appreciate the language every time I use it. There isn’t another language that has given me such satisfaction - so far. Most accommodate the interpreter / compiler. This one accommodates humans.
- deleted 3y ago[deleted]
- djur 3y agoHow does this syntax make code slower and more error-prone? According to the article, it actually saves allocations in common cases.
- Alifatisk 3y agoLove this series
- deleted 3y ago[deleted]
- xutopia 3y agoThis is sweet like candy. Such a fun series!
- deleted 3y ago[deleted]
- happytoexplain 3y ago> please note that `...` in the code below is the exact valid syntax, not “code omitted for a blog post” We need a standard for this. When I'm writing example code, or redacting real code, I usually opt for an ellipses with spaces: `. . .`
- Pxtl 3y ago`...` is the standard. Don't make language features that use three-dot-ellipsis as a keyword. Just like don't make a language where "Hello world" is a special string with special significance, or where variables named foo, bar, baz, quux, or i have special meaning. I mean, it's nobody's fault but your own if you make a language feature that breaks industry conventions.
- elaus 3y agoBoth Java and JavaScript use the three-dot-ellipsis `...` (spread, varargs), so I'm not sure if it 'breaks industry standards' if Ruby uses them as well.
- Bootvis 3y agoR and its predecessor from 1988, S-Plus, as well.
- Pxtl 3y agoIt's a lot less confusing when it's only appearing in the function's parameter signature where you're declaring parameter names instead of the method body. It's not common to see educational snippets with ellipsis in the function signatures - they're usually in the body somewhere.
- DylanSp 3y agoGo uses it as well.
- happytoexplain 3y agoThree-dots is valuable real estate. I don't begrudge the various languages that use it - their use cases are usually worth it.
- Pxtl 3y agoUgh, I'm just skimming this but it sounds like quick forwarding syntax in Ruby went through a mess of hiccups in development, which is sad, because I think the obsession with C/C++ as the gold standard of language development for so long really held the industry back. I love languages that offer convenient forwarding - the verbosity of forwarding in traditionalist C/C++-style programming languages is imho a big source of the horrible abuses of inheritance. Such a shame it's mostly provided in languages that are too dynamic-typed for my tastes.
- icambron 3y agoIt's more that Ruby has a bunch of pre-existing quirks related to the various things you can pass to a function (positional, named, blocks) and even what functions are (methods, blocks, closures) and that quirkiness creates complexity for simple-sounding things like forwarding syntax.
- throwanem 3y agoWhy are there so many kinds of things that can be passed to a Ruby function?
- yebyen 3y agoYou can pass positional arguments because that's how arguments have typically been passed in the history of computing. You can pass keyword arguments because they are much less ambiguous to use when a method signature is changing; you never have any confusion about which method argument is missing. You can pass positional and keyword args together in a way which is rigidly formalized since Ruby 3.0 because, at one point in history, you could pass a hash, you could pass positional arguments, and you could pass keyword arguments, and nobody was ever able to tell reliably what you were doing: https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/ https://www.ruby-lang.org/en/news/2019/12/12/separation-of-p... You can pass a block because in Ruby, a block is an object like anything else. And you can pass an anonymous block because in Ruby, the "yield" keyword is an idiom that's commonly used with anonymous blocks. The curly braces and the "do" keyword that are both common idioms in Ruby are nearly identical forms of anonymous block. The throwaway answer to your question is that you can pass anything that is an object, and in Ruby since anything is an object, you can just pass anything! I haven't read the whole article, but I get the sense that I shouldn't read much into the clickbait headline, since it looks like this is a really thoughtful show or treatment of all the neat handy things that Ruby lets you do with various types of arguments, and not a hit piece! whew relieved
- throwanem 3y agoI would call it a thoughtful treatment of how late versions of Ruby solve a problem that well-designed languages never have in the first place.
- endorphine 3y agoI intuitively expected this to get downvoted but I'd like to hear opinions of the people who downvoted this, wrt how much of this flexibility is a design flaw (or accidental complexity?) and how much it is expected given the history and evolution of the language.
- pawelduda 3y agoI love these series and agree. Ruby was already very expressive language and IMO few major versions ago was a good time to reconsider this area of development in favor of something else. I think contributing to <<optional>> static typing would have had higher RoI...
- ReflectedImage 3y agoProgramming languages shouldn't have two competing two type systems in them. Static typing in a scripting language like Ruby is just poor engineering.
- Timon3 3y agoStatic typing for JavaScript hasn't turned out to be poor engineering - it helps massively and has become the de-facto norm. Similarly, static typing in Python is a massive help and keeps getting better. Why would Ruby be any different?
- ReflectedImage 3y agoBecause JavaScript is the worse programming language in common commerical usage today. It was designed over several decades by browser manufacturers. Absolute anything else would be better than it. Static typing in Python is a complete disaster when it's used on real commerical projects. I've seen the code thank you very much.
- Timon3 3y ago> Because JavaScript is the worse programming language in common commerical usage today. It was designed over several decades by browser manufacturers. Do you mean "the worst"? There are plenty languages that are worse, and that are still in use. It's not great, but it's also not as terrible as you're making it seem. > Absolute anything else would be better than it. Okay, what does that have to do with static typing? Or are you saying that Typescript is better than Javascript? If static typing can make such "the worse" language better, why can't it improve other languages as well? > Static typing in Python is a complete disaster when it's used on real commerical projects. I've seen the code thank you very much. You make it seem like the alternative, not having static typing, is in any way better. No, it's definitely not - having e.g. your IDE know the types of values to help you in refactoring is extremely valuable, as is having static type checkers tell you about issues before running your code. You either have unknown type problems because you're missing test cases, or you're re-building a static type system in your test suites. There is no way around verifying your assumptions about types if you want to build stable software.
- aeonik 3y agoDoesn't Clojure support this kind of variadic pass through? Admittedly it's a bit more complicated than Ruby's syntax, which I find to be a bit ironic. I'm not sure if Clojure has something equivalent to &block... I think you would just pass a function in Clojure since they are first class? https://john2x.com/blog/clojure-destructuring.html https://john2x.com/blog/clojure-destructuring.html
- orthoxerox 3y agoI think Clojure prefers macros for things Ruby uses blocks for. For example, `with-open` is a macro that accepts the "block" as a `& body`, while a similar mechanism in Ruby would just take a block/closure that looks like any other statement block.
- eduction 3y agoNot so, much more typical to just take an anonymous function for things ruby uses blocks for. For example, map, or filter (select in ruby), or reduce. “with-open” is a macro because it needs to do something more complicated (create a bunch of bindings then close each one created, in addition to executing a fn body where those bindings are available). Passing an fn is preferred because functions are more broadly preferred in Clojure code to macros, for both practical (more composable) and cultural reasons.
- orthoxerox 3y agoAnonymous functions return from themselves, whereas a block is a special kind of closure that returns from the caller. It's probably less important in Clojure since it is more functional and doesn't use explicit control flow much.
- aeonik 3y agoThis is the part that fascinates me about Code Blocks so much. Is it like an extra break or return statement at the end of it that bails out of the context of whatever method it's running in? Or does it actually return back to the original all site after nested passes of the Code Block?
- kristiandupont 3y agoI recently stumbled upon something in JS (specifically NodeJS and a few other runtimes) that might be of interest here: AsyncLocalStorage (https://nodejs.org/api/async_context.html https://nodejs.org/api/async_context.html). It allows for storing data specific to the current asynchronous context. I've been using it primarily for adding logging prefixes and managing authentication in Postgres with Row-Level Security (RLS). Essentially, it offers a server-side alternative to "prop drilling," where you repetitively pass the same parameter through a chain of function calls.
- klysm 3y agoC# has the same thing and I use it for the exact same things
- namtab00 3y agowait, what? can you point to a feature name / doc / example?
- texuf 3y ago[dead]
- dtech 3y agoThis is extremely similar to thread local, a feature in many languages including C#.
- jcparkyn 3y agoI'm pretty sure they were talking about AsyncLocal<T>, which is not quite the same as ThreadLocal (values are persisted even when an async flow transitions across).
- klysm 3y agoYes it’s different but conceptually similar in the sense of ambient execution context. I prefer implicit variables like scala has but it gets the job done in C#.
- gizmo 3y agoAt some point you’ve got to stop messing with syntax. It plain sucks not being able to run anything on a linux machine that is on a LTS schedule. The constant churn of version updates that fix some things but break other things is a massive time waste. It’s practically impossible to remove features from a language. If you keep adding “improvements” to your language you end up with the unholy mess that is modern c++
- UncleEntity 3y agoIsn't the whole point of LTS to outsource all this nonsense to the maintainers of the distro? Back when I was heavily involved in blender development I'd sometimes have to pause my hackery while waiting for fedora to catch up with whatever version of python blender was using because I didn't want to bork my system by upgrading python (again!). Well(...) I also wanted to ensure that it would run off libs from the repos and this was a little higher priority than being on the cutting edge so it was a sacrifice I was willing to make. The only time this caused any significant delay also coincided with one of the open movies and they didn't want to merge what I was working on until after production which meant it didn't matter either way. I don't ruby but it seems like a nice way to do something like: def apply(callable, ...): callable(...)
- regularfry 3y agoIn practical terms, if you're using the distribution's interpreters for anything other than running code supplied by the distro, you're going to be in a world of pain. That is the whole point of a distro: to supply a known-good set of mutually compatible software. Expect to be building your own environments if you want to run things that are not in your distro.
- pixel8account 3y agoI can't relate. I'm a Python programmer and I don't think I ever used a Python version other than the one provided by my distro. Unless you run a very outdated/"stable" distribution, interpreter versions are no more than few years old. Most serious projects don't just jump on the new language version on the day it's released, certainly not my projects, so I never had the need to run a bleeding edge interpreter.
- hu3 3y agoThis (syntactic sugar) is the kind of thing that wouldn't even be considered in Go. And that's fine. I find it interesting that Go and Ruby can be placed at two different ends in so many spectrums and yet both still managed to be popular. Goes to show that trying to build THE ONE TRUE LANGUAGE THAT WILL UNITE ALL DEVS is a fool's errand.
- Gh0stRAT 3y agoI think that Javascript's massive success with the terrible syntax it used to have goes a long way toward confirming your hypothesis.
- loloquwowndueo 3y ago“Used to have” :)
- Gh0stRAT 3y agoHaha yeah, I was being charitable to avoid starting a flamewar ;)
- vkou 3y agoDo people do real work in JS in 2023, or do they do it in languages that compile down to JS?
- dtech 3y agoIgnoring compiling and polyfilling for older JS versions, Typescript is extremely popular. While it's compiled, all things beside the type system are from Javascript by design including syntax.
- epcoa 3y agoProbably of all people a lot of ruby acolytes do since a sizable portion of that community is a DHH personality cult. And plain JS is the 2nd best language ever made in that realm.
- gardenhedge 3y agoWow, that is some ugly code
- block_dagger 3y agoMigrating some projects to use … was a pain but it is a better pattern imo. Rspec expectations around arguments can be tricky.
- agubelu 3y agoI tried picking up Ruby some time ago, when RoR was at its popularity peak and seemingly everyone couldn't shut up about how “elegant" and fun Ruby was. After trying it... I can say that it's for sure someone's idea of elegant code, and I can see why many people like it, but it just didn't resonate with me at all. Too many syntax quirks that didn't look particularly nice to read IMO.
- nyjah 3y agoIt’s funny because I think overtime this is the same sentiment that seeped into the Ruby community. It used to be with pride when something worked with ‘magic’, but Ruby and even rails have both gotten away from that mentality, and I think for the better.
- pdntspa 3y agoRuby's weird for me in the sense that it is the language that most directly maps to my thought processes. Ruby's syntax feels extremely natural, but I first learned Java and C like a lot of my other cohort. Maybe it's because the first programming language I was truly good at was Perl
- stouset 3y agoRuby has the highest ceiling for clean, elegant, and expressive solutions to problems in any language I’ve ever seen. For small teams of (one or two) highly-experienced programmers with compatible vision, you can produce truly incredible programs. It also has the lowest floor. With the usual makeup of teams of frequently-rotating mostly-junior engineers who don’t have the experience, understanding, and restraint to use Ruby’s more… let’s call them idiosyncratic features, the sheer volume of completely inscrutable crap that can be put out in a given amount of time is truly breathtaking.
- Lammy 3y agoI feel the same way and I'm so happy I gave the language another chance after getting turned away by the behavior/attitudes of the Rails community back in "The Day". Ruby made me love programming again :)
- chrismorgan 3y ago> In a radical variant of this, Perl’s sub doesn’t have a syntax for arguments declaration at all Actually, Perl has had signatures <https://perldoc.perl.org/perlsub#Signatures https://perldoc.perl.org/perlsub#Signatures> as an experimental feature (requiring `use feature 'signatures'`) since 5.20.0 (May 2014), and they’re considered stable (requiring `use v5.36` or later) since 5.36.0 (May 2022): use v5.36; sub test($x, $y) { print "x=$x y=$y\n" } test(1, 2) # prints x=1, y=2
- zverok 3y agoOh, thanks! Added a footnote to the article.
- thowaway91234 3y agoAs a lifelong rubyist, this is definitely what I would say "useless". Maybe it's just because I've been stuck in Ruby 2.6 ~~hell~~ land for so long but I remember seeing a colleagues leetcode challenge for a job interview that used Ruby 3.1 and he used a bunch of these new syntax sugars and I was really rubbed the wrong way by them. Code the omits arguments is neither more readable (what exactly is getting passed around here?) or maintable (what happens when you have some condition that may apply to one of the arguments, then you just need to unwrap all the "nice" things and do it more traditionally). The elipsis ... especially rubs me the wrong way because multiple periods either .. or ... denotes range types, but now we have a special case where ... is something completely different. Bah humbug. They seem nice in clean blog scenarios with trivial examples, but in my experience they are not conducive to writing readable and maintable code. Thankfully I can just disable their use in my projects (for the most part) with rubocop. All the hip young kids can write their magic code, I'll stick to more straightforward constructs that anyone can figure out.
- deleted 3y ago[deleted]
- deleted 3y ago[deleted]
- deleted 3y ago[deleted]
- bradgessler 3y agoI’ve been using Ruby since 1.7 and think the new syntax is fantastic. I hope you’re not weaponizing Rubocop in team or community projects in a manner that discourages “hip young” Rubyists from learning and exploring new ways of pushing the language & runtime forward.
- thowaway91234 3y agoWe have developers of various experience and skillsets that come and go, sticking to a subset of language features with minimal magic has made it easier to onboard and get people productive. We have massive codebase, and sprinkling these new sugars around in arbitrary places to be lindmines for them isn't worth it to me. From a business perspective, we're not too concerned about pushing the language forward, we're focused on creating value for our customers - the language is just a detail.
- phendrenad2 3y agoLove it. Anything that makes Ruby feel more like Smalltalk and less like Python is a win.
- 3cats-in-a-coat 3y agoThis article make it look like understanding Ruby code has become an absolute hell. I don't mean understanding as in "I get what this demo snippet is doing kinda", but as in "what is exactly happening here, how to edit it, and what might break if I edit it". Feels like the antithesis to Perl's write-only code. Ruby is read-only code.
- djur 3y agoWhen is the last time you used Ruby?
- zverok 3y ago(Author here) I don't think this corresponds to my experience. I am working as a staff engineer in big production codebases (with all the traits of those: some code is good, some is bad, some is unrecognizable legacy, sometimes we are in a hurry and write awful code, sometimes we have time for refactoring etc.) And my observations about the logic and perception of the features are drawn from the practice of code reviews, mentoring new people, and discussing ways of solving tasks in this environment. Obviously, I am frequently a driver of new code practices, but I am also trying to be a good person and a good colleague and notice how comfortable people are with various parts of the codebase, various idioms, etc. One of the main topics of this article series is uncovering the language's logic and intuitions (to stop perceiving it as a "bag of random syntactic features you need to learn or should guess") and using those intuitions for code that is, yes, better for the reader, but the code that can be created in a quickly-changing production environment and rewritten fearlessly.
- 3cats-in-a-coat 3y agoI'm not objecting to your article, but to this language and its (you called it!) "useless Ruby sugars". People sometimes use humor to mask suppressed pain, I've noticed. A smart individual can adapt to any environment and its quirks and thrive. But some of their capacity always goes towards serving the "quirks adaptations". It's kind of like GPT. It's a smart bot, and if you ask it to answer a math puzzle by writing backwards in Romanian haikus - it will. But the effort to make haikus in backwards Romanian make its math puzzle answer that much more likely to be wrong. I have no shadow of a doubt that people who are used to Ruby know every shade of gray in how to forward arguments through byzantine syntax. Much like PHP programmers have zero issues with every function in stdlib randomly switching needle/haystack parameter order, or remembering which identifiers are case sensitive and which aren't, and the mix of conditions where an identifier needs a $ in front or doesn't need it. Or which one of 10 different stdlib APIs doing kind of the same, but in different state of deprecation and introduction they should use. Or the fact PHP has a type system, but not for the most common data type (array), and there are two modes of validating parameters (strict and non-strict) which can be switched on and off per file and bomb on you unexpectedly when combining both, despite your code is logically correct in isolation. It's trivial stuff to them. They can juggle all this and more. But someone coming from outside would take one look and say "how about no". Because PHP for all its advancements is not a good language. And Ruby is also not a good language. In fact, it's clearly getting worse over time.
- bradly 3y agoHere is common use case I use for this in my Rails apps: This is the most common way I use it: class ApplicationService def call raise NotImplementedError end def self.call(...) new(...).call end end class MyService < ApplicationService def call(service_specific_arg: 123) #... end end
- viralpraxis 3y agoI’ve been using the same structure for years :) But I prefer to replace ‘raise NotImplementedError’ with ´raise “Not Implemeneted”’ because that exception has different semantics (method unavailability on the current platform)
- prognostikos 3y agoI also avoid `NotImplementedError` as it inherits from `Error` instead of `StandardError`. This can bring down services like job queue processors that rescue `StandardError`.
- still_grokking 3y agoWhat is this code good for? I can understand what it does but I don't get the intend behind that. (I'm not a Ruby programmer, so maybe I miss something "obvious")
- kazinator 3y agoANSI CL: (defun wrap-foo (&rest args) (apply #'foo args)) TXR Lisp: (defun wrap-foo (. args) (foo . args)) The (. args) syntax (consing dot not preceded by item) is equivalent to args; if we write it that way, we are not using any syntax that didn't exist in 1958.
- mvdtnz 3y agoRuby is a truly hideous language that keeps getting uglier by the year.
- oglop 3y agoI love the ellipsis. Ruby has made so many good choices as it moved into 3 and I’ve only been happier and happier with it. I also write my Ruby Seattle style, so I’m one of those weirdos.