Hunter McMillen
Hunter McMillen

Reputation: 61540

Ruby class variables are null

I am defining a bunch of class variables in my Ruby class and initializing them to a value, but when I print them in my to_url function they are all null, can someone tell me why???

class BarChart < GoogleChart
    @axes_prefix       = "chxt="
    @data_scale_prefix = "chds="
    @type              = "#@@type_prefix" + "bvg"
    @size              = "#@@size_prefix" + "800x375"
    @colors            = "#@@color_prefix" + "4466AA"
    @axes              = "#@axes_prefix" + "x,y,x,y"
    @x_axis_index      = "0"
    @y_axis_index      = "1"
    @x_axis_label_index  = "2"
    @y_axis_label_index  = "3"
    @axes_label_position_prefix = "chxp="
    @axis_range_prefix          = "chxr="

    def initialize(title, data, labels, x_axis_label, y_axis_label)
        @title, @data, @labels, @x_axis_label, @y_axis_label = 
            title, data, labels, x_axis_label, y_axis_label
        super(@title, @type, @size)
        to_url()
    end


    def to_url()
        puts @axes_prefix, @data_scale_prefix, @type, @size, @colors, 
        @axes, @x_axis_label_index, @y_axis_label_index, @x_axis_index, @y_axis_index
    end


    def start()
    b = BarChart.new("CHART", "0,1,2,3,4,5,6,7,8,9", 
    "ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE", 
    "Zero to Nine", "Numbers").to_s()
    end

if __FILE__ == $0
    start()
end

Any ideas would be great.

Thanks.

Upvotes: 0

Views: 737

Answers (2)

Victor Deryagin
Victor Deryagin

Reputation: 12225

You are defining that variables directly in the class, which means they belong to the class itself, not to it's instances. You can directly access them from the class methods, but not from instance methods (which is your to_url). If you want them to be accessible from instance methods - define that variables in another instance method, for example, in initialize.

Upvotes: 2

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24637

  1. It's not a class variables, it's a instance variables. (@@foo - it's class variable)
  2. You can't initialize them outside of the methods. Move them to the initialize method, for example.

Upvotes: 3

Related Questions