I have created a class for example
@@min = 0
@@max = 0
def initialize(min, max)
@@max.min = min
@@max.max = max
result = Result.new(1, 10)
@@ 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
You don't need to create default values like this:
@@min = 0 @@max = 0
You can do it in the
def initialize(min = 0, max = 0)
This will initialize
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
.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