Hacker News new | ask | show | jobs
by derefr 1115 days ago
The thing about Ruby is that it has uniform syntax — a.b for any a+b mean "send a message :b to a." So `self.foo` (and `self.foo = bar`, too!) are possible to write, but these are always interpreted as message sends (to the :foo and :foo= methods, respectively), not as direct field accesses. The "syntax-ness" of @ and @@ show are that you're specifically breaking out of† the paradigm of "everything is a message send", to instead "just" access a field. It's what makes this make sense:

    def foo # define a getter method
      @foo # in terms of a field access
    end
How would you write that, if the field access was spelled `self.foo`? The language wouldn't be able to tell that you're not just recursively calling the getter!

---

† Though, technically, you're not breaking out of the paradigm; @foo is short for self.instance_variable_get(:@foo). It's message-sends all the way down, until you hit natively-implemented methods.

2 comments

> How would you write that, if the field access was spelled `self.foo`? The language wouldn't be able to tell that you're not just recursively calling the getter!

You can require parentheses for method calls put methods and fields in separate namespaces.

https://play.rust-lang.org/?version=stable&mode=debug&editio...

Elixir supports paren-free calls but the default linter and formatter won't let you use them except for a few whitelisted DSLs. I've never missed not having them.

In languages that require parens for method calls, not using them usually gets you a method handle. Which is still in conflict with a field reference — usually because methods are just function-pointer-typed static fields.
That's why I said "you can" rather than "you must". And linked to an example that of a language with the property I described.
As someone who infrequently had to touch Ruby code, this was maddening. Years later, I only now am finding out what was going wrong and a better sense of what search terms to use.

As I said I'm a big propoenent in languages being approachable for those infrequent one-off cases. I've been burned by the challenge of updating the "handful" of Perl and Ruby scripts (and Perl was my first language). This is why I advocate against Lua and 1-indexing when the target audience is programmers and it isn't a "primary" language.

I also have to touch Ruby code from time to time, so when I found out I don't quite understand what "@" and "@@" mean (other parts, even blocks, were kinda more or less apparent), I... went and read the docs. Took me an hour or two but now I know what "@" and "@@" mean and actually think they're a pretty ingenious solution.