Hacker News new | past | comments | ask | show | jobs | submit login
The Ruby Style Guide (rubystyle.guide)
77 points by garrettdimon on June 14, 2019 | hide | past | favorite | 47 comments



Oh fun another style discussion! :-)

My own taste is for a "book style": write the code like you see in good books. I agree with most of this guide, although I'm pretty loose and case-by-case in practice. I've gradually added rubocop to lots of my projects, but then I wind up disabling tons of the rules.

I'm sad all the Ruby guides I've seen ban "and" and "or". I don't find them to be such an issue, and they are nicer to type & read. For one thing you can say `foo or raise "msg"` but need parens to say `foo || raise("msg")`. On team projects I sigh and go along with it, but it is a shame.

Speaking of "book style": I have a bunch of Python books with atrocious style, e.g. no spaces between operators or even between function arguments. How can anyone read that? I even see this from high-quality publishers like O'Reilly. What is going on with the Python world? Are their thumbs tired from all that indentation, so they leave out spaces everywhere else? ;-)

I really want to write a SQL style guide. There seems to be almost no consensus. My own formatting is idiosyncratic and not super principled, but I feel it is the most readable and expresses structure the best. It looks like this:

    SELECT  a, b
    FROM    t1
    LEFT OUTER JOIN t2
    ON      t2.t1_id = t1.id
    WHERE   t2.c = 'foo';
(EDIT: Sorry, t2.c = 'foo' is a pretty dumb thing to do in an outer join. :-)

Other people like to do one or more of these things:

    SELECT a
         , b
      FROM t1
           LEFT OUTER JOIN t2 ON t2.t1_id = t1.id
     WHERE t2.c = 'foo';
In other words:

- lead with the comma in SELECT.

- ragged left edge but line up all the single spaces in a column.

- indent the joins.

Anyway sorry for the rambling. :-) There is some observation that committees spend 90% of their time on trivial details and hardly discuss any of the important stuff, and style is no exception. But who doesn't like giving their opinion? :-)


> I'm sad all the Ruby guides I've seen ban "and" and "or". I don't find them to be such an issue, and they are nicer to type & read

I generally prefer `&&` and `||` for purely aesthetic reasons; they're much taller characters, so I can easily see the division between clauses. `and` and `or` look too much like identifiers (even with keyword syntax highlighting), so my eyes tend to gloss over them at first glance.

Out of curiosity, was the use of `&` in "type & read" intentional to try to demonstrate your point? My preference is interestingly the opposite for natural language; using tall punctuation like that feels too obtrusive for me in the middle of what usually is a bunch of lowercase letters.


> Out of curiosity, was the use of `&` in "type & read" intentional to try to demonstrate your point?

Ha ha, no! :-) I think I often type "&" as a micro-tie and "and" as a macro-tie. In other words "&" connects two words (or "a, b, & c"---and btw always with an Oxford comma, which should be obviously correct to any self-respecting programmer :-) but "and" connects clauses. This comment is probably the longest I've ever thought about it, but I do believe it is a persistent habit in my typing. Maybe to be consistent I should start using "|" too. :-)

I've never thought about tall/short for Ruby conjunctions, but it seems like a plausible motivation. Lots of typographers say people read by seeing ascenders|descenders (okay that one was on purpose :-) and can even recognize words where the letters are removed and you just draw an outline around them.

EDIT: I think I've been working too hard this week. Bikeshedding style it not normally how I'd spend my Friday morning, but it's pretty fun. :-)


A symbol for "or" would be so extremely sensible in this pattern.

And there was one.

Just as "&" abbreviated "et", a-sort-of-i-thingy abbreviated "vel"(= "or"). I have no idea why only "&" thrived and the "or" one faded. Now it's long forgotten, hiding at Unicode point U+026B


Interesting, thanks for sharing that! I once spent a summer helping a library write one-sentence summaries for medieval Latin books, and all the abbreviations and ligatures made the paleography really tough! But actually we do have a common symbol for "or". I used it once in that comment, but then I switched to "|" for fun: "/".


Those are all really interesting points! The division between clauses and lists is a really great insight; I think for me, I actually have the opposite preference ("&" for clauses and "and" for lists), although in practice I don't find myself using "&" in English very much.

> people read by seeing ascenders|descenders (okay that one was on purpose :-)

I actually totally missed that you had done that until you pointed it out :)

> and btw always with an Oxford comma

Now we've definitely found some common ground!


Funny, I've been wanting to do/working on a SQL style guide myself, with a big emphasis on using leading commas because of the readability and easy-adjustability. I do something like this:

            SELECT  
                a, b
            FROM
                t1
            LEFT OUTER JOIN t2
                ON t2.t1_id = t1.id
            WHERE   
                t2.c = 'foo'
            ;


I don't like it. :-) Splitting each clause into two lines makes my eyes stumble. I can't read it as effortlessly as I read normal text. At least you are left-aligning the keywords though. :-)

I have two spaces after my SELECT because when you press tab that's where you wind up next. Keeping things tab-aligned lets you easily type it out without a lot of fuss. I think that gets you much of the benefit of your broken-line clauses without impairing reading flow.

Also on a monitor vertical space is scarce, so I'd like to keep that reasonably compressed.

I get how leading commas makes it easy to re-order projections but I've never heard anyone say it makes them easier to read. :-) (I have no problem putting them on multiple lines if you have a lot or some are long.) And I'd rather optimize for readability over not needing to add/remove a comma.

I can see why you'd indent `ON` although I prefer to keep its conditions at the same level as WHERE.

I also do the semicolon at the bottom thing a lot.

Anyway it's fun to trade tastes. :-) SQL is surprisingly hard to rule on when it gets complicated. I doubt I am consistent once I start adding subqueries, CASE, etc.


This is also my preferred style. This means the keywords are separated from variables, and there is no code-based arbitrary space-alignment.


> I'm sad all the Ruby guides I've seen ban "and" and "or"

Well, as you no doubt know it's about the precedence - "and" and "or" are much lower, which can lead to confusing behaviour since conceptually they overlap so much with && and ||. I confess I had to go and refresh my memory of their exact behaviour, and I've been using ruby for a decade. I guess I agree with the "ban" since reading code can be confusing enough without having to think about which flavour of "and" you're using, but I guess I can see the use case.

Your (first) SQL example is exactly the style I would write, by the way! It's funny how conventions seem to arise by some emergent crowd phenomenon. I remember several years ago I realised that hey, I don't even need to capitalise the keywords - but the result looked so "wrong" after years of reading them capitalised that I still do it anyway.


I would do your SQL like this:

  select a, b
    from t1
      left outer join t2
        on t2.t1_id = t1.id
    where t2.c = 'foo'
      and t2.d = 'bar';
- Lowercase

- I don't like that use of variable number of spaces to try to align things you did in both your examples. Doing that kind of thing in code generally leads to having to readjust that spacing whenever a new line is added or removed.

- Constant-width indentation indicates structure. "left outer join" is part of the "from" clause, so it's indented further. "on" is part of the "left outer join" clause, so it's indented further.

Among languages, I imagine SQL is the one with the most varied styling among those who use it.


> I'm sad all the Ruby guides I've seen ban "and" and "or". I don't find them to be such an issue, and they are nicer to type & read. For one thing you can say `foo or raise "msg"` but need parens to say `foo || raise("msg")`.

To me your example seems to be the proper use of the `and` and `or` statements - unless the team decided that the `raise("msg") unless foo` variation was preferable.


The only thing I really don't like here is non indenting when inside case. I know that technically it's not a block, but in practice I find it much less readable


Everyone agrees with you on readabilty. I think that's why they had to add this bit about this (A bit of History) section...

"This is the style established in both "The Ruby Programming Language" and "Programming Ruby". Historically it is derived from the fact that case and switch statements are not blocks, hence should not be indented, and the when and else keywords are labels (compiled in the C language, they are literally labels for JMP calls)."


No, everyone does most assuredly not agree on readability when it comes to case statements. Flat case reads better, and indenting it would be like indenting "elsif" and "else" in an else statement.


yeah, even more, taking the example from the style guide, if lines are short enough, I love doing:

  case
  when song.name == 'Misty' ; puts 'Not again!'
  when song.duration > 120  ; puts 'Too long!'
  when Time.now.hour >  21  ; puts "It's too late"
  else
    song.play
  end
even more, for simple if/elses, many times I do:

  if member.coding_style.vertical_align?
  then friends << member
  else member.show_example(code)
  end


I made a comment on this thread[1] in 2014, and it was closed two days ago. I wondered why... guess this is why!

1: https://github.com/rubocop-hq/ruby-style-guide/issues/273


This thread is interesting to me, since I've changed my mind on this topic since I originally commented. :P

I blame Rust, and macros.


I don’t fully get your point. There is no official style guideline for Ruby.


I'm not sure what your point is either. Mine was "oh, there's a website now; they must have been reviewing old issues to prepare for the launch." There is no "official" style guide, you're 100% right, but I'm not sure what that has to do with this.


Oh, got you. I thought you were implying some conspiracy to kill conversation or something. Nvm.


Ah, yeah, no worries! I was not :)


It's actually an interesting thread. My take would have been to use comma when it's something we intend to modify, no comma when it's not. So intent is explicit.

Like:

    STATES = [
      :success,
      :error
    ]

    SUPPORTED_LANGUAGES = [
      "en",
      "es",
      "fr",
    ]


Yeah, you're right. I was triaging and cleaning up the open issues prior to launching the new site.

Now that the guide has more editors I'm optimistic that we won't end up in a situation with that many non-triaged tickets down the road.


I'll never understand Ruby's obsession with implicit return.

When reading code, my eye will immediately notice the `return` keyword and will have less to think about in terms of code execution.

The `return` keyword makes for great readability.


I much prefer this, though I accept its not without problems in some cases. I find that say Javascript in comparison has a lot of syntactic noise; it's all annoyingly boiler-plate.

Maybe JS's implicit-return-in-arrow-functions is a better compromise.


I feel JS has few syntactic noises but which part are you referring to?


There's also StandardRB, it's like StandardJS but for ruby:

https://github.com/testdouble/standard

Lightning talk about it here:

https://www.youtube.com/watch?v=uLyV5hOqGQ8

Edit: I posted it on its own if you want to discuss:

https://news.ycombinator.com/item?id=20186231


Hard to swallow without any reasons written behind each decisions.


The Ruby Style Guide has been around for a long time now, this is just a nice update.

The guide has received ample feedback and edits/additions over the years, with an emphasis on reaching a consensus amongst senior ruby developers and open source contributors.

I believe that adding justifications or reasons for each guideline would make the guide harder to read and search. The way it is written now is succinct enough to pass on to junior developers, and allows a company to centralize style around a well-established set of rules rather than reinventing the wheel.


Agreed. I'm just happy to have a style guide that's tasteful enough and well-known among Ruby users. For me, one big advantage of the guide/Rubocop is being able to let other people worry about the little details and variations.


There are some explanations. For example there is a link to a discussion at the end of https://rubystyle.guide/#consistent-multi-line-chains


All languages should have gofmt at this point. Debating code style is a waste of everyone's time.


Parens for method calls should only be used when things get ambiguous. Nothing bugs me more than seeing ruby code cluttered up with that garbage. I know, I know, but that's my personal bikeshed and I'll happily die on the roof of it.


80 char line length in 2019?


I know, on the surface it seems silly, but there are a couple of reasons I've found 80 chars makes things easier in real world workflows in 2019:

* Split panes in editors. With 80 chars, you can usually have two panes on screen along with a file tree, on most laptop screens. This is pretty nice to have.

* Code reviews in a web interface like Github/Gitlab - 80 chars means usually there's no need to pan, even when your browser window isn't full screen


Enforcing 80 chars on everyone for those reasons doesn't feel justifying.

It will definitely make people use weird variable names instead of meaningful ones.

  is_included = true
could turn into,

  inc = true #included or increment?
That's a far worse side effect than other points raised in this thread.


Even worse, abbreviations are terrible as there is one way to write a word correctly, and lots of ways to abbreviate it, so now you have to keep track of that too.

Was it inc? incl? incld? includ? in? incldd?

Now you have to break flow to go check. There's many ways it could be written and a chance for bugs to be introduced if you accidentally pick the wrong style. And when you read it, does the inc mean incorporated? included? includes? including? incapable? incestual?


That's a fair point, though I'll say in my experience, it's not been the case. If it were, I wouldn't do it as I agree with you that it outweighs the benefits I mentioned.


There are many good reasons for that IMO:

* Too long lines are hard to read. For text 11 words per line are recommended, otherwise your eyes will loose track. 11 Words is roughly 60 characters, but code is indented so you need a bit more.

* Some people look at your code in an 80-column terminal, if you use more, this would be rude.

* Some people use a GUI diff tool that displays the code side by side, so that's already 160 characters.


- Breaking lines at only 80 chars would make it read horrible by splitting lines in the middle of syntactic contexts.

- Unless that's your team's preference, you're not helping anyone.

- Same as above.


Python's PEP8 recommends 79 characters.


slightly worse :)


This one is genuinely awful. It makes me take style guides less seriously on the whole.


How about 1 space indentation? Just to be able to squeeze even more stuff into the 80 char limit? 0 space is a bit too extreme :)


Spaces for identation? seriously?


I do believe most style guidelines for other programming languages prefer spaces over tabs - I believe spaces have "won" (the merit of each is a whole other debate).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: