9

I have a module with a class variable in it

module Abc
  @@variable = "huhu"

  def self.get_variable
    @@variable
  end

  class Hello
    def hola
      puts Abc.get_variable
    end
  end
end

a = Abc::Hello.new
a.hola

Is it possible to get @@variable inside Hello without using get_variable method? I mean something like Abc.variable would be nice. Just curious.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
huhucat
  • 159
  • 2
  • 6
  • possible duplicate of [How can Ruby's attr_accessor produce class variables or class instance variables instead of instance variables?](http://stackoverflow.com/questions/895747/how-can-rubys-attr-accessor-produce-class-variables-or-class-instance-variables) – Andrew Grimm Jul 26 '11 at 23:06

2 Answers2

4

You cannot access @@variable directly (i.e., Abc.variable) within the scope of the Hello class in the module Abc. Why? Because, when the Ruby interpreter sees something like Abc.variable, it would think variable as class/module method of Abc.

It is important to think the Ruby way when programming in Ruby.

apaderno
  • 28,547
  • 16
  • 75
  • 90
karthiks
  • 7,049
  • 7
  • 47
  • 62
  • Aside note: If you wish to get over such thoughts to a large extent I have shared my learnings in the recently held Ruby Conf India 2011. Please do feel free to watch my talk at http://kartzontech.blogspot.com/2011/06/ruby-conf-india-2011.html and give your ratings and feedback. Most importantly, read the last of the slides where I mentioned the resources that helped shape my thinking the Ruby way. – karthiks Jul 26 '11 at 17:14
-1

try this

Abc.class_variable_get(:variable)
Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
Dileep
  • 1
  • Please expand your code or supplement with an explanation or you risk having your answer deleted by the moderators. – sshashank124 Mar 31 '14 at 09:00