Newbee Dev Newbee Dev - 2 months ago 6
Ruby Question

Initialize class object variable in RUBY

I have created a class for example

class Result
@@min = 0
@@max = 0
def initialize(min, max)
@@max.min = min
@@max.max = max
end
end

result = Result.new(1, 10)
result.max


Same as other lang. like php, C# etc I have created a class and pass a value and since it has initialize method it will should now contains the object values but when I try to print out

puts result.min
puts result.max


it says undefined method
min

Answer

In Ruby, @@ before a variable means it's a class variable, what you need is the single @ before the variable to create an instance variable. When you do Result.new(..), you are creating an instance of the class Result.

You don't need to create default values like this:

@@min = 0
@@max = 0

You can do it in the initialize method

def initialize(min = 0, max = 0)

This will initialize min and max to be zero is no values are passed in.

So now, your initialize method should like something like

def initialize(min=0, max=0)
    @min = min
    @max = max
end

Now, if you want to be able to call .min or .max methods on the instance of the class, you need to create those methods (called setters and getters)

def min # getter method
  @min
end

def min=(val) # setter method
  @min = val
end

Now, you can do this:

result.min     #=> 1
result.min = 5 #=> 5

Ruby has shortcuts for these setters and getters:

  • attr_accessor: creates the setter and getter methods.
  • attr_reader: create the getter method.
  • attr_writer: create the setter method.

To use those, you just need to do attr_accessor :min, this will create both methods for min, so you can call and set min values directly via the instance object.

Now, you code should look like this

class Result
    attr_accessor :min, :max
    def initialize(min=0, max=0)
        @min = min
        @max = max
    end
end

result = Result.new(1, 10)
result.max #=> 10