Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] Is there a way to create a private instance variable? #3800

Closed
andyfleming opened this issue Dec 29, 2016 · 4 comments
Closed

[question] Is there a way to create a private instance variable? #3800

andyfleming opened this issue Dec 29, 2016 · 4 comments

Comments

@andyfleming
Copy link
Contributor

I'm aware of instance and class variables, but is there a way to create a private instance variable?

class Person
  def initialize()
    @example_one = "instance variable"
    @@example_two = "static/class variable"
    # No way to create a private instance variable
  end
end
@RX14
Copy link
Contributor

RX14 commented Dec 29, 2016

Instance variables are always private. The only way to "expose" an instance variable is through getters/setters, either manually created or using the getter, setter or property macros.

@andyfleming
Copy link
Contributor Author

I see that now. Sorry about that.

For anyone else that comes across this, here's the snippet from the docs that shows creating a getter/setter for an instance variable.

class Person
  def initialize(name : String)
    @name = name
    @age = 0
  end

  def name
    @name
  end

  def age
    @age
  end
end

From https://crystal-lang.org/docs/syntax_and_semantics/new,_initialize_and_allocate.html

@mgarciaisaia
Copy link

Don't get confused - that code defines getters, but there are no setters there.

A setter looks like this:

def instvar=(value)
  @instvar = value
end

But the best way to deal with this is using the macros for defining getters, setters or accesors (both getter AND setter).

@andyfleming
Copy link
Contributor Author

Thanks! Someone else explained the concepts a bit more clearly for me.

I opened an issue to improve the documentation here: crystal-lang/crystal-book#62

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants