Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I'm not a Ruby programmer

and (without any form of negative judgement), this is why

> a couple of these things just look completely wrong

to you, because they're idiomatic of Ruby.

First, lack of return.

A random example in Rails's ActiveSupport[0]:

    def to_s
      "(GMT#{formatted_offset}) #{name}"
    end
It just reads like ":to_s is defined as being a String constructed this way". Note that formatted_offset and name are resolved as methods in the context (i.e self), and self. is simply omitted, which is also idiomatic.

Not only functions always return something (their last statement's return value), every statement actually returns something, so

    foo = if a == b then 1 else 2
works and is used, but also with case/when, and whatever you can think of. With proper indentation this is perfectly sane and readable, and avoid redundant, 'side effect' (from the point of view of code flow) assignments, easing comprehension and refactoring, while making mistakes less likely (foo will always and obviously be assigned something).

What's more, a Ruby construct known as blocks are used with methods (such as Enumerable#map or Enumerable#select) needing return values, and omitting return is a readability and typing boon.

That's not to say return has no use, but then when you use it, you mean it, so that it is used in match/exit pattern methods, where you're doing some checks, and dispatch-return according to various situations, i.e you return early.

It is also used in Procs, which differ from lambdas in that a return will return from the caller, not the Proc.

Second, right-side if.

This aids readability when you're concerned about doing a number of sequential tasks, and some of them are conditioned. All possible tasks are aligned, and all conditions are on the right side. An absence of condition means "always". Sounds almost like column-based source code (fortran, RPG on AS400...).

You mention scanning down the file, but idiomatic ruby would not make you scan down the file: you would be faced with a function, whose size would make its structure/pattern apparent, and with such a pattern the logic would be readily seen, dangling on the right side.

Such conditions are often used with the first part of this discussion, so that you see immediately what is returned right there on the left, possibly conditioned.

[0]: https://github.com/rails/rails/blob/5fe88b11f11bb3b30bc23c57...



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

Search: