11 ms·
Why Ruby Is More Readable Than Python
- strangattractor 4y agoIt's not.
- transfire 4y agoNice to see some of the differences clearly laid out.
- EdwardDiego 4y agoSubjective opinion presented as fact? Say it ain't so.
- cassianoleal 4y agoWeird criticism. If I say that halloumi is better than tofu, do you not assume I'm talking about my personal opinion? Do I need to make it painfully clear that it's my subjective opinion? Taste, as much as readability, are subjective so that can be assumed. Also, if you read the post, you'll have noticed the author is constantly saying "I find this more readable", and engaging the reader with "what do you think?" questions on each point made, which makes it very obvious that they're presenting a personal, subjective view.
- philovivero 4y ago> Do I need to make it painfully clear that it's my subjective opinion? Yes. Because a sentence written in the Arial font, as much as I might find that font distasteful, is more readable than the same sentence written by a Captcha-generator. A bubble-sort written in Golang is easier to read than the same bubble-sort written in Brainfuck. Yes, there are exceptions to the rule (I imagine someone who knows Brainfuck, but doesn't know Golang for example), but the rule is very clear in both cases. The clickbait flamewar-inducing headline is saying, essentially, Ruby is the former in the examples I gave, and Python the latter. We're not junior-high students trying to one-up one-another with cute gotchas. We're technical professionals. We should expect higher standards of communication skills from other technical professionals. If you mean "I have a useless opinion that no-one should care about," then state it. If you mean "I have statistical evidence that most technical professionals will be able to comprehend programs written in Ruby better than the same programs written in Python," then state it. But don't expect a good reaction when you say the former, while tricking us into thinking you were saying the latter.
- anothernewdude 4y agoEvery sentence said by a person is their opinion. That's what saying things is. Even the "obvious" counter-example, lying, works because every sentence said by a person is their opinion. You couldn't lie if it wasn't.
- cassianoleal 4y ago> If you mean "I have a useless opinion that no-one should care about," then state it. I don't. People will care about. Not everybody but some will, and that's fine. > We should expect higher standards of communication skills from other technical professionals. Reading comprehension is just as important as writing. I expect my peers to know that an opinion is subjective without me needing to say so. For instance, I would have expected you to not gloss over my last paragraph on the previous post, just as much as I would have expected you to understand, by reading the article, that everything written there is the author's opinion but I guess that wouldn't have been such a good straw man.
- klodolph 4y agoThis is a matter of style; we encourage writers to write this way and trust that readers know the difference between fact and opinion. Go through a typical college writing class and the teacher will direct you to delete phrases like “I think” and “I believe” from your writing.
- djbusby 4y agoUse the Active Voice.
- ignurant 4y agoNew Rails 8 feature? (I’ll see myself out).
- mikkergp 4y agoI get this, and I've started to write this way, because it gets a better response; but it feels to me like it's designed to maximize an emotional response and not a cognitive response, and find I have less trust in people who write this way (Which is most things, i get) I do wonder how this style of writing has impacted the psychology of argument, I imagine there are others who read this style of writing and assume it is written in stone or as an objective statement, and not a subjective one. This may just be human nature.
- arcticfox 4y agoI have to say I appreciated but also laughed at the sheer number of the qualifiers you're discussing in your post... "it feels to me", "I find I", "I do wonder", "I imagine", "this may" I find it makes for less combative discussions. So I like it.
- klodolph 4y agoI'd say that these qualifiers are much more useful in informal communication, like HN, and inappropriate for long-form stuff like essays. Essays are longer, more coherent, and denser.
- drewcoo 4y agoThe author relies on you, the reader, to exercise thought? Say it ain't so.
- EdwardDiego 4y agoMaybe the blog post title should then be "Why a Ruby dev finds Ruby more readable than Python". And the post body reads: "Because that's what they're used to." Fin. Roll credits. Personally, I find Python more readable, because I know Python better than Ruby. I don't think there's anything inherently more discoverable about @@ to denote a class field. Python instance fields are all prefaced with self, so a bit of cursory Python learning makes it clear. But yes it feels weird that you can't declare them upfront. (And it gets weirder when using libs like Pydantic where class level fields are used to describe instance fields in (de)serialised objects.) IMO, Java's static keyword is far more discoverable because it's far easier to google. As I discovered when trying to figure out what an @ meant in a TS import statement. But, I'm not writing a blog post about why Java is more readable than Ruby, because that's just, like, my opinion man.
- voidhorse 4y agoRight, but the goal of an essay is typically not to disseminate certified, proven fact beyond all possible dispute. In fact, many essays argue points that are inherently fuzzy—e.g. an essay on your interpretation of your favorite novel will make an argument for your interpretation but it will never prove that it is the one true interpretation of a novel since that’s ridiculous and impossible. Often the goal in writing an essay is to share a personal view or experience, and sometimes to get others to share their thoughts on a topic. For example, if you did write an essay on why Java’s static is better than Ruby’s @, it might lead others to engage with you, share their thoughts, and help you learn more or modulate your own viewpoint as a result. Montaigne, the oft-touted father of the essay as a form of literature, in fact explicitly wrote essays as a means of self-reflection and self-exploration. This isn’t some technical paper coming from a research lab or standards body, it’s someone interested in a particular topic sharing their thoughts on that topic, potentially influencing others and potentially being influenced themselves.
- pessimizer 4y agoYou get facts from measuring devices, not people. And even then, when you read the number on the display, or try to figure out if the device is functioning correctly, the facts instantly become opinion again. If it helps you, prefix everything that everyone ever says from now on with "It is my opinion that..." e.g. "it is my opinion that it is 6 o'clock." The "that's just your opinion, man" thing is the only thing I'd like to see as a universally ban-worthy offense on the internet. It's an entirely empty statement that can be made about anyone who said anything, is always a bitter defense against somebody who took the risk of putting themself out there, and shouldn't be seen as anything but a troll. And I'm fully aware that this is my opinion, which is why I said it and not someone else.
- voidhorse 4y agoNo. If the author were truly trying to present this as fact there’s be far more remarks against anticipated disputes “pythonistas will say… blah blah blah… but here’s why they’re wrong” or more extreme statements, “it’s an objective truth that… only fools would deny…” The author doesn’t do any of this, in fact the author is barely even arguing a point. It’s pretty clearly an opinion piece. Human beings have been writing like this and differentiating between fact and opinion for centuries. Demanding that all writing be watered down to hedge-laden statements and statistics would land us in a very boring world indeed. People can read, judge, and think for themselves. We don’t all approach literature like computers reading instructions.
- diegoholiveira 4y agoCurrently I’m working in a large ruby codebase and previously I was working with Python and Go. Until this moment, I do prefer Python.
- zinclozenge 4y agoBoth Python and Ruby can become extremely hard to read if you start leaning heavily on the metaprogramming parts. When I was learning ruby on rails circa 2012 I frequently got frustrated with libraries writing their own DSL.
- kuang_eleven 4y agoInteresting. Even with the examples given, I found Python considerably easier to follow, with the possible exception of the inheritance example. Just goes to show how subjective it all is!
- synergy20 4y agoI agree, ruby's @ and @@ probably will make it a bit harder to read for anyone that is new to both languages, plus it seems more lengthy to me, python wins.
- brigandish 4y agoAs an aside, it's bad practice to use @@ variables (IMO), they're easily clobbered. Class instance variables are much better[1]. I might also add, if you create getters for an instance variable then you don't need to use the @, except in the getter itself (and you don't even need to do that as there is the `attr_reader` helper for that). [1] https://maximomussini.com/posts/ruby-class-variables https://maximomussini.com/posts/ruby-class-variables
- philovivero 4y agoIndeed. I started working with Ruby for at least a year before I started working with Python. To this day I still can't do anything useful in Ruby, and I'm proficient in Python. Python is far more readable and comprehensible than Ruby. Haven't even bothered to read TFA because it's just weird flamewar bait.
- joshuamorton 4y agoYes, up until the mention of multiple inheritance, I thought the post was mediocre satire.
- drcongo 4y agoSame. The amount of boilerplate and "unnecessary" symbols in Ruby make it considerably less readable to me. The Python examples aren't just readable, they're glanceable.
- kayodelycaon 4y agoI find Ruby to be more straightforward than Python. In isolation, I’d argue Ruby is greatly more readable and understandable than Python. In practice, Ruby code isn’t. Once someone starts doing advanced meta programming, get the shovel, because you’re going to kill whoever wrote it and need to bury the body. Rails largely gets away with this by having opinionated design, good documentation, and a large user base who have already written answers to your questions.
- hangonhn 4y agoThat really mirrors my experience as well. Ruby is a very consistent language but I think one of the things people get really enamored with Ruby is the meta programming -- myself included and soon you're going to need a bunch of context in your head to understand all the "magic" that's happening.
- tmm84 4y agoI feel this comment so much. Having never done Ruby programming and was given a task from a client to work on a Ruby project. I didn't think much at the time because having dealt with all kinds of programming challenges I was confident in taking it on. Much to my surprise the amount of "magic" methods, meta-programming and anonymous classes in the source code required a lot of hand holding from the devs who had been working on it from the start to teach me how to find/read and debug everything the "Ruby" way.
- chrisallenlane 4y ago> required a lot of hand holding from the devs who had been working on it from the start to teach me how to find/read and debug everything the "Ruby" way. Yes. And even just _finding_ relevant bits of code is difficult and painful, because you can't simply `grep` for the names of these metaprogrammed methods. They're simply not in the codebase.
- projectazorian 4y ago> Once someone starts doing advanced meta programming, get the shovel, because you’re going to kill whoever wrote it and need to bury the body. Metaprogramming in application code is one of those trends I'm glad is behind us. Might look cool and work great initially, but a painful refactor is near inevitable once there's been some turnover on the team and the problem space shifts in a way that invalidates the underlying assumptions. Library code is another matter though.
- piva00 4y agoUntil metaprogramming, autoloading, DSLs and everything that eventually makes Ruby code unreadable takes place due to personal preferences. Ruby is clever, it can be beautiful, but I've never seen a good codebase using it grow well without enforcing strictly opinionated ways of writing it to ensure maintainability. Which breaks a lot of the expectations of some Ruby developers that chose the language because they like to write it in their own way.
- projectazorian 4y ago> Ruby is clever, it can be beautiful, but I've never seen a good codebase using it grow well without enforcing strictly opinionated ways of writing it to ensure maintainability. Which breaks a lot of the expectations of some Ruby developers that chose the language because they like to write it in their own way. Yeah, this is one of the major disadvantages of Ruby. Every Ruby shop of any size has its own idioms and internal code style, which means a lot of unnecessary overhead when onboarding new people. Even experienced devs need to take some time to feel out their team's norms. The expressiveness also lends itself to bike shedding - I've seen many a PR comment questioning why a dev chose method A versus method B, where method B is an alias of method A. Probably an hour of staff time spent on something that has zero impact on functionality, maintainability, or performance.
- drewcoo 4y ago> without enforcing strictly opinionated ways of writing it to ensure maintainability But a team cannot have its own opinions with Python. They're already built in.
- dragonwriter 4y agoA team can absolutely have its own opinions about Python. “There should be one— and preferably only one —obvious way to do it” from the Zen is very much aspirational, rather than a declaration of an immutable truth about Python and it's ecosystem.
- hzhou321 4y ago> Ruby is clever, it can be beautiful, but I've never seen a good codebase using it grow well without enforcing strictly opinionated ways of writing it to ensure maintainability. I believe every good maintainable software needs an enforcing strictly opinionated ways of writing it to ensure maintainability. Language need be general to be useful. Any language can create utterly unmaintainable code. If you shift "opinionated" into the language, it is less easy to write unmaintainable code, but it is also more difficult to write fitting maintainable code because that "opinionated" opinion may not best fit (and usually can't best fit) a specific application, a specific team, and a specific set of experience. On the other hand, if we shift "opinionated" to the programmer, the language inevitably need add more meta-programming ability or simply more ways to do the same/similar thing. The code can easily become unmaintainable under less experienced programmers who are not opinionated and aren't disciplined. The current programming culture expect programmers to be commodities, thus favors opinionated languages and idiomatic code. I can easily imagine a shift in culture that favors experienced and opinionated and disciplined programmers, where different set of languages will be favored. Today's software, once grow to certain size, are all quite unmaintainable.
- drewbug01 4y agoI find it odd that getters and setters are implemented in Ruby … manually. attr_accessor is the idiomatic way to do it (or attr_reader / attr_writer if you want more granular control).
- chrisseaton 4y agoIt's for encapsulation. You can switch them out for a method with logic without changing your interface. I don't know Python very well - is that the same there?
- syntaxfree 4y agoYou can override the relevant dunders, but why would you.
- chrisseaton 4y ago> but why would you To migrate an API - that's what I said.
- drewbug01 4y agoApologies - I mean “the author implemented their getters / setters in the ruby example by writing actual methods by hand. The idiomatic way to do it in ruby is to simply write: “attr_accessor :title”. There’s no change in interface needed in the ruby example if you decide that you want to replace that with fully-written getter/setter methods like the post shows; attr_accessor generates exactly those same signatures for you.
- Nullabillity 4y agoYes, you can replace attributes with properties without changing the consuming code. For example: >>> class Foo: ... @property ... def bar(self): ... return "hello from a property" ... @bar.setter ... def bar(self, value): ... print(f"tried to replace bar with {value}") >>> Foo().bar 'hello from a property' >>> Foo().bar = "asdf" tried to replace bar with asdf
- Buttons840 4y agoOne of my favorite HN comments talks about the differences between Python and Ruby way back in 2009: https://news.ycombinator.com/item?id=682364 https://news.ycombinator.com/item?id=682364 Still applicable I think.
- pelagicAustral 4y agoI write Ruby for a living and I'd argue than in my case it has to do with blocks, which are so much more relatable coming from C# than tabulation-based code blocks... To me, it feels much more natural.
- woodruffw 4y agoRuby, like so many other good things, is best enjoyed alone :-) I've loved every Ruby codebase that I've written. I still consider it one of my favorite programming languages, and (in pedagogical terms) one of the best languages for learning "practical" functional programming (point-free style, blocks as intuitive closures, &c.). But when I work with others, I find that all of the things that I love are obnoxiously clever to others, and that the things they love are obnoxiously clever to me. Python isn't immune to that kind of cleverness, but subjectively it's not as common. I chalk that up to the higher pain threshold for doing really obnoxious metaprogramming in Python, a lower community tolerance for unidiomatic interfaces, and (broadly) better QA tooling (RuboCop is great, but MyPy + isort + Black + flake8 is really hard to beat).
- klipt 4y agoMy theory is this is also why Lisp never took off. Powerful macros are wonderful for the solo programmer but difficult for a large team to reason about.
- eointierney 4y agoProgrammers are not Computer Scientists, and the world is poorer for their conceit.
- no_wizard 4y agoI think this is a tooling problem, as far as LISPs go, because unlike C, you (as far as I remember, perhaps I'm wrong) aren't relying on the compiler to fill in the bits, the macro is just a shortcut, if you will, to functionality. Not always transparent, but it should be solved with correct tooling. I think the bigger problem was LISP was far too long tied to LISP Machines, rather than being able to run independently on any hardware, which helped C and Pascal gain traction early
- pjmlp 4y agoLisp itself precedes the Lisp Machines for about 20 years, and was available in UNIX workstations as well, in fact that is where Allegro Common Lisp started.
- anothernewdude 4y agoRuby is too flexible for me to ever want to work on a Ruby codebase. Also, those ruby examples aren't readable, I have no idea what your sigils and double sigils are doing beyond giving me Perl flashbacks.
- deleted 4y ago[deleted]
- jefftk 4y agoI initially thought this article was being sarcastic. After each comparison when they said Ruby was more readable I thought they were joking, until we got to multiple inheritance.
- jez 4y agoThere's more than one way to write the corresponding Ruby snippet. If I had been writing it, I might have translated it something like this: class BlogPost class << self attr_accessor :count end self.count = 0 attr_accessor :title, :body def initialize(title, body) @title = title @body = body @published = false BlogPost.count += 1 end def publish! @published = true end def to_s = @title def count = self.class.count end This avoids needing to understand what `@@count` means, and lets you use the same syntax as in python: `BlogPost.count += 1`. Or, if I were in a codebase using static type annotations with Sorbet, I'd do something like this[0]. To each their own, write code in the language and style that makes the most sense to you. [0] https://sorbet.run/#%23%20typed%3A%20true%0Aclass%20Module%3B%20include%20T%3A%3ASig%3B%20end%0A%0Aclass%20BlogPost%20%3C%20T%3A%3AStruct%0A%20%20class%20%3C%3C%20self%0A%20%20%20%20sig%20%7Breturns%28Integer%29%7D%0A%20%20%20%20attr_accessor%20%3Acount%0A%20%20end%0A%0A%20%20prop%20%3Atitle%2C%20String%0A%20%20prop%20%3Abody%2C%20String%0A%20%20prop%20%3Apublished%2C%20T%3A%3ABoolean%2C%20default%3A%20false%0A%0A%20%20def%20initialize%28title%3A%2C%20body%3A%2C%20published%3A%20false%29%0A%20%20%20%20super%0A%20%20%20%20BlogPost.count%20%2B%3D%201%0A%20%20end%0A%0A%20%20def%20publish!%0A%20%20%20%20%40published%20%3D%20true%0A%20%20end%0A%0A%20%20def%20to_s%20%3D%20title%0A%20%20def%20count%20%3D%20self.class.count%0Aend https://sorbet.run/#%23%20typed%3A%20true%0Aclass%20Module%3...
- gmalette 4y agoThat’s without even mentioning the footguns available in @@count Jez!
- jez 4y agoAh sure, this alternate implementation assumes that the BlogPost class is final and never subclassed. If you plan to subclass BlogPost, the translation is not identical, as the alternate implementation would not keep track of a global count of posts across all subclasses, only of `BlogPost` instances exactly.
- gmalette 4y ago
- dylanz 4y ago“ I didn't work hard to make Ruby perfect for everyone, because you feel differently from me. No language can be perfect for everyone. I tried to make Ruby perfect for me, but maybe it's not perfect for you. The perfect language for Guido van Rossum is probably Python.” … “I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language.” - Yukihiro Matsimuto
- mberning 4y agoMaybe I am an outlier, but the few jobs I have had with a ruby codebase have been super fun and relatively easy to pick up. Every project has a learning curve, and I have experienced some pretty bad ones that were not written in Ruby.
- tragomaskhalos 4y agoMoving to Python from Ruby, one very early scarring experience was battling trying to get the length of a string, before eventually discovering len() - a free function, whereas in Ruby (OO purist that it is), everything is a method. Well I thought this was rather silly and counterintuitive of Python, and said so in some forum or other, whereupon i discovered the very passionate views of folks who have come down hard on one side or other of this debate. So, lesson learned: keep one's opinions on such matters to oneself, as one man's banquet is another's poison. In which vein, it would be splendid if this comment did not occasion another screed about the manifest glories of __len__ to enlighten us heathens.
- isitmadeofglass 4y ago> was battling trying to get the length of a string This makes it sound like you where trying to learn the language by typing in random stuff and just hoping something runs. Yes every language will leave you scared if your path to learning it doesn’t even involve reading a single page about its most basic functioning.
- tragomaskhalos 4y agoWhat an extraordinarily patronising response ! Firstly, not 'scared', 'scarred' - merely a bit of harmless hyperbole to indicate a briefly frustrating situation. Secondly, this is not monkeys-at-typewriters, merely an expectation that Python would conform to any other object-based language and have a public method on string to report its length. This should be a discoverable, not an RTFM case.
- doteka 4y agoWhile I agree with you the grandparent was unnecessarily patronizing, they do have a point. “Built-in functions” is the first chapter of the documentation following the introduction, there’s no way to miss it. If you don’t even skim the introductory documentation, I’m not exactly sure what you expect to happen. Python is not Ruby nor is it Java, and it predates both. Why would it follow the idioms of those languages?
- no_wizard 4y agoDoes Ruby have support for just exporting functions around? All these examples are class based. When I was a Python programmer, we found functions scaled infinitely better over time (with the exception of data classes, unfortunately) for complex business logic especially.
- makeitdouble 4y agoI think the smallest footprint would be a module ? Importing a module add all the functions declared in the module to your current scope. From memory, you can't restrict to one or two specific functions, but in practice it's rarely an issue.
- thr0wawayf00 4y agoNo, unfortunately. This is one thing I've always wished Ruby had.
- remram 4y agoRuby is object-oriented, for better or for worse. Similar to Java, you can have static methods, but they have to live in a class (or module in Ruby's case).
- thr0wawayf00 4y agoI assumed OP was asking if Ruby had a way to import specific functions from a module (i.e. "from math import pi".) the way that many other languages (like Python) support. Instead, Ruby forces you to require the entire module, which makes tracking public interface usage harder.
- kayodelycaon 4y agoIf you're looking for that level of granularity, you can implement each method as a class, or as a static method on a class or module. Then it's fairly easy to figure out where things are used.
- 4y ago
- coldtea 4y agoI think he proved the opposite case -- and gave examples, too!
- yarg 4y agoSurely there's a correlation between ease of reading and ease of compilation? I'm thinking in terms of avoiding back-tracking in your syntax. E.g.: regices are hard as shit to read, and I don't think that back-tracking helps (ab + c)* Or *+(ab, c) The first says ab, no - it's the union of ab and something, something is c, no - it's one or more of those. The second says one-or-more of the union of (ab) and (c). Why haven't languages pushed that way?
- remram 4y ago> regices Please no. It's bad enough that people insist on using foreign plurals in English, let's not pretend "regex" is some latin word (it's just REGular EXpression).
- yarg 4y agoWords are about the only damned thing where mere belief conjures existence.
- yarg 4y agoAlso, if you're going to bother to reply, reply to the content - rather than the terrible pun that I through in for the sake of my own bored amusement. I'm a fucking programmer (at very least I'm a dude commenting on HN) - I know what regex is short for.
- nimih 4y agoThe article closes with this thought: > While both languages are much easier to read than say, PHP or Java, [...blah blah blah...] Which leads me to wonder: Have there been any serious studies of the readability of programming language syntactic and semantic conventions? For instance, a good friend of mine (whose day job is working as a software consultant, and whom I imagine would disagree with the author's assertion) finds it extremely difficult to understand python code in particular due to his dyslexia, and I wonder how common such problems are, both as a % of people and % of programming languages.
- remram 4y agoPHP has a bunch of hacks that are here for technical reasons. Function names are inconsistent and terse because they were inherited from C, and there is the historical name-resolution quirk. The prefixed variable names don't bring anything and are not here for any good reason (compared to shell where "naked" identifiers are interpreted as strings). A lot of the object-oriented features had to settle for unusual tokens like backslashes. You might find that the PHP syntax is objectively problematic. For Java, Rust, etc it's a bit different. I would say that's up to taste. Using "public static" is very verbose but more obvious than @ or _ prefixes.
- nimih 4y agoI agree with your specific assessments here, but I was trying to get at the question of whether there are meaningful and measurable differences in the broad-scale accessibility of e.g. whitespace-centric syntax vs lispy syntax vs curly-brace syntax. Admittedly, it's hard to tease this apart from the standard library and communal conventions of any given language: Java occasionally devolving into an endless sequence of ProducerFactoryFactory.newProducerFactory().initializeProducerBuilder(new ProducerBuilder())... certainly impacts its readability in a practical sense, just as the Haskell community's perhaps ill-advised love of point-free programming and highest-order polymorphism doesn't always do it favors on the readability front. Those sort of details seem like they'd really complicate a rigorous and systematic study, but on the other hand, lacking a good methodology has never stopped _other_ supposed quantitative studies of programming languages as they relate to e.g. "developer productivity" and "defect rates," so who's to say...
- javier_e06 4y agoWith better unicodes I wish computer language could use fancier characters to express loops, conditionals and in general without using the english language. goodbye to [if, else, switch, break, lastly, each etc..] let us crate a language that uses no letters but unicode symbols to express abstractions. Like emojis.
- TylerE 4y agoPlease no. Font ligatures are bad enough
- cassianoleal 4y agoYou can use Emojicode [0] if you'd like. I'd rather keep using Ruby, Go, Python, etc but to each their own. [0] https://www.emojicode.org/ https://www.emojicode.org/
- javier_e06 4y agoIt makes sense to go the emoji way. We already get emojis on our IDEs with lightbulbs, lightnings and the dreaded red x mark.
- yedpodtrzitko 4y agoI read through the article waiting the whole time to see that "this is more readable", but I found nothing. Also I'm not sure if the Python examples are so blatantly wrong on purpose or if the author read one Python tutorial beforehand and then decided to write this article. For example this: > In Python, you will never do post.__str__ for example. Instead, you’ll do str(post) No you dont. You do the same thing you did with `puts post` in your Ruby example: `print(post)`, which will call `__str__()` method. > In Python, it’s easy to accidentally write to the count attribute — which can break your program. To address writing into attribute directly - you can use @property decorator, which will stop you into writing into given attribute, unless you add a setter. However the main problem in this fabricated example wouldnt be that you can break your program by accidentally writing into an attribute. I'm not sure how common is it in Ruby, but mixing the instance variables together with class variables this way seems like a bad design, and that is what will break your program. Regarding the Django example - ok that is far from perfect, but comparing a framework which maintains backward compatibility for years with code you write from scratch without worrying about anything is barely a fair comparison.
- TylerE 4y agoThis lost me when the first example showed named arcs in the python version, and none in the Ruby version. Gues what? They aren’t required in python either
- eddof13 4y agoagreed, that was like the first thing I noticed which broke a lot of the credibility
- ilrwbwrkhv 4y agoThe dunders in python make my eyes bleed. It stands out in an otherwise neat language, due to its significant whitespace.
- DangitBobby 4y agoWhen you need them, you need them, but apart from __init__ (and __str__ if you're doing Django) you mostly won't need to touch them. After working with the language a while, I honestly don't see them as ugly anymore.
- alanbernstein 4y agoHmm. I knew how to read python before I bothered starting to learn it. There are language primitives in Ruby that I have no experience with. So the premise is simply wrong...
- hosh 4y agoI didn't get Python until it was pointed out to me that Python is procedural. The objects in Python is more like how I wrote "object-oriented programming" in Pascal with records and procedures. All the intuitions one would expect in Ruby with respect to encapsulation is inverted in Python. I have noticed that this extends to Ruby's approach to bundler, and Python's approach to virtualenv/et al. Knowing this made me less irritated at Python.
- filoeleven 4y agoBoth options looked bad from the start, and only got worse. Why do I need a class with getters and setters, in-place mutation, a pointless toString and a (mutable!) static count variable, instead of: { title: “a grumpy programmer’s rant about objects”, body: “Wait, hear me out y’all…”, published: true } Both the Python and ruby examples have no post-ID, so mutating in-place is an extra-bad idea. It should not be the default. Why does the static count variable exist? These things are all stored in some list (memory, db, whatever, perhaps multiple places) and we can count any subset of those that fits our purpose. What happens when I’m asked to add draft posts? Should I only update the count only if published == true? It depends on whether I’m looking at “number of blog posts” as a user or “my drafts” as an author. Why does the toString exist? Nobody uses those in real app code for end-users, they are a convenience for developers. Use a better REPL/debugging environment that can handle pretty-printing data. If you need more customization, use a function. Please, just use plain data wherever possible. Please use languages that support and encourage using plain data. Please push mutation to the edges of the system, and please carefully control the in-place updates. The computers in our pockets are more powerful than anything that existed on earth before 199x, yet the industry is still acting like we’re running them on 8086 microprocessors with 640k RAM. Let’s grow up and think more deeply about building robust systems which can evolve with changing needs. EDIT: Changed published to true, because this is basically that.
- rvieira 4y agoWhat is your view on why did Ruby missed Python's current spot? Did it miss the data science/ML boat?
- em-bee 4y agoto me it comes down to taste. in those examples, python looks more readable to me (and easier to write) because it is more concise. the less code that i have to scroll through, the more readable it is. (to a degree. APL is compact but not concise because it uses short symbols for things that would be readable words in other languages) getters and setters are boilerplate. if you want them, you can use them in python too. common operations should be easy, uncommon operations should be possible. python is doing that. ruby in this case forces me to treat a common operation the same as an uncommon one. personally, i only want getters or setters if they do something beyond plain return and assignment of the value, like a range or type check for example. that way, when they actually matter, they stand out in the code. the same goes for access to class variables. i get it, there is some beauty in having every class look the same. you can just write it all down without much thinking. and when you need a custom setter, it's already there and easy to modify, whereas in python i may have to do some extra work, add the setter, and make sure its use is enforced. it's a trade-off. +() vs __add__() to define a + operator? sure, +() looks more elegant, but in the end the code is the same, __add__() stands out well enough, and while i too would prefer +(), it's not something i'd bother complaining about. there are other things that are more irritating. and finally, single inheritance vs multiple inheritance. an age-old discussion with good arguments on both sides. pick your preference.
- k_sze 4y agoYears ago, I tried to teach myself Ruby because Rails was all the rage. But I could not, for the life of me, remember which symbol means private, which meant protected, which meant public. There was no affordance to the symbols, and I have never seen any other OOP language that does that. And then I moved on to Python and Django, and found the lack of real private/protected/public in the Python world utterly liberating. The more I programmed in Python, the more I appreciated “we’re all consenting adults”. The more I thought about it, the less reason I find in trying hide anything via protected/private. For example, if I understand correctly, in .NET/Java, anybody with enough determination (and runtime permission) can use your protected/private stuff via reflection anyway.
- ahefner 4y agoI look at the __init__ and initialize methods in the examples here and remember why I don't want to use either of these languages. What useless boilerplate, just to define a simple type.
- jmconfuzeus 4y agoAh, that's why my analytics is showing HN traffic. OP here. Thanks for sharing my friend. I'm not a Ruby programmer but I wrote this post while learning Ruby and after having read through the entire Sinatra code base. I was surprised at how much easier Ruby code is to read even though I've been a Python programmer for the past 6 years.
- motbus3 4y agoI read the article and I am more convinced that Ruby is, if anything, more complicated than anything.
- dzsekijo 4y agoWhat I enjoy about Ruby over Python the most is not intricacies of the OO implementation or delicacies of metaprogramming, but a good support for functional style. In ruby, statements are expression-like, they have a return value. Also, with Ruby it's easy to break down code to consecutive pure blocks. Condiser the following task: take /proc/kallsyms in Linux, that lists symbols in kernel, in an '<address> <type> <name>' format, like: 0000000000000000 A fixed_percpu_data 0000000000000000 A __per_cpu_start 0000000000001000 A cpu_debug_store 0000000000002000 A irq_stack_backing_store 0000000000006000 A cpu_tss_rw 000000000000b000 A gdt_page ... let's make stats on it -- how much of each type is present? Wanna get the result ordered by number of occurrence. In Ruby: # ruby -rset -e '$<.readlines.to_set.classify { |l| l.split[1] }.transform_values(&:size).sort_by { |_,v| v }.to_h.tap { pp _1 }' /proc/kallsyms {"V"=>1, "w"=>2, "a"=>14, "R"=>98, "W"=>154, "A"=>328, "B"=>655, "D"=>2910, "b"=>3097, "T"=>22289, "d"=>34424, "r"=>49904, "t"=>55346} Of this method call chain, first and last are impure (as they do I/O), the intermediate ones are pure. In Python you'll have to grind through it procedurally. (Unless you use reach out to some advanced libs... https://gist.github.com/richardbann/5b363096de6b3de2e8178ccebb0f3a03 https://gist.github.com/richardbann/5b363096de6b3de2e8178cce...)
- sylvainr65 4y agoNot on topic but a little rant about dark themes. After years of reading code displayed in dark mode on a white page (high contrast), I still wonder why. It's really hard to see, at least for me. Most of the time, I end up selecting the whole piece of code to have white text on a black background - it's not as good as black text on a white background, but it's much better than dark blue or dark red on a black background. This interesting article uses dark red for operators (".", "=", "<", etc.). This is one of the worst choices. On a dark background, please do not use dark color.
- Thetawaves 4y agoHaving worked on both python and ruby applications in my professional life, I am shocked that anybody could claim that ruby is in any way ... readable.