brewster
brewster

Reputation: 4502

how to access class instance variables VS class methods

I recently ran into a conceptual ruby issue with accessing class instance variables via the class instead of the matching class method. for example...

class Test
  @foo = nil
  def self.foo foo
    @foo = foo
  end
end

How can i access @foo from Test without renaming self.foo? There are obviously simple ways around this, but this is more of a functional Ruby question than an actual issue.

Upvotes: 0

Views: 94

Answers (2)

danh
danh

Reputation: 62676

I'd name the setter more explicitly and provide an explicit class getter...

@foo = nil

def self.foo=(foo)
    @foo = foo
end

def self.foo
  @foo
end

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118289

Using Module#class_eval or Object#instance_variable_get.

class Test
  @foo = nil
  def self.foo foo
    @foo = foo
  end
end

Test.foo(12)
Test.class_eval('@foo') # => 12
Test.instance_variable_get('@foo') # => 12

Upvotes: 2

Related Questions