alfi
alfi

Reputation: 21

How to use 'attr_accesor'

I have a class with a private method:

class MyClass
  attr_accessor :my_attr

  def some_mth?(num)
    # I want to use my_attr as a variale @myattr here
    #and here i want to check if arr include num
   @myattr.include?(num)
  end

  private

  def some_pvt_mth
    @myattr = [1,2,3,4]
    for example generation array here
  end
end

When I call @myattr inside some_mth, my variable @myattr is nil

How to use variable @myatt inside class, in every method is it possible?

How do I do it properly?

Upvotes: 0

Views: 151

Answers (2)

AJFaraday
AJFaraday

Reputation: 2450

You do not need to define attr_accessor in order to use an instance variable within the defined class. It's purpose is to create a 'getter' and a 'setter' method, but those are only needed for other classes to access the data.

This is a class:

class Foo
  def initialize
    @my_attr = [1,2,3,4]
  end

  def attr_includes?(x)
    @my_attr.include?(x)
  end
end

There's no attr accessor, but this will work.

The attr accessor essentially includes this code in your class...

class Foo
  def my_attr
    @my_attr
  end

  def my_attr=(x)
    @my_attr = x
  end
end

But if you don't want that, you can just leave it out, and access the variable via other methods (such as your include example).

Upvotes: 2

user9595038
user9595038

Reputation:

You have to define the instance variable value first:

class MyClass
  attr_accessor :my_attr

  def initialize
    @myattr = [1, 2, 3, 4]
  end

  def some_mth?(num)
    @myattr.include?(num)
  end
end

Upvotes: 1

Related Questions