3

For some reason this code will work:

class Foo
  @foo = "foo"
end

Foo.new.@foo # => "foo"

And I see, this feature has been used in standard library specs, but it seems to be undocumented one. So, the question is, what is the status of the feature, should one use it?

WPeN2Ic850EU
  • 995
  • 4
  • 8
  • 1
    I guess one could use this for now, but why? You can always use `Foo.new.foo` right? – SalmonKiller Jul 08 '18 at 02:37
  • 1
    For `Foo.new.foo` you need to define it. For example with something like `getter :foo`. It looks more like an issue and I'd suggest [to report it](https://github.com/crystal-lang/crystal/issues). Usually undocumented features should not be used if you want to keep your code compatible. It might be in standard library for some time until something will be fixed and shipped libraries will rely on a proper mechanisms. – ony Jul 08 '18 at 07:29

1 Answers1

2

This feature is currently used for internal purposes, but it is discussed to limit external access to instance variable. A behaviour similar to protected methods might be useful.

The issue for this is crystal-lang/crystal#6066.

I would generally avoid this feature, as it is undocumented and very likely to be changed at some point.

Johannes Müller
  • 5,581
  • 1
  • 11
  • 25
  • 1
    It's also used to automatically define struct equality. You can basically use it if you want to, but it's not recommended. You should normally use getters. – asterite Jul 08 '18 at 16:12