Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize class object variable in Ruby

Tags:

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

like image 445
Beginner Avatar asked Sep 26 '16 02:09

Beginner


1 Answers

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 if 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
like image 119
davidhu Avatar answered Sep 23 '22 00:09

davidhu