Reputation: 4153
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
Upvotes: 9
Views: 21683
Reputation: 10434
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
Upvotes: 15
Reputation: 1458
Without knowing the context here it's hard to say exactly what you're looking to do. I suspect what you actually want is an instance variable. In which case you would do:
class Result
attr_accessor :min, :max
def initialize(min, max)
@max = min
@max = max
end
end
Class variables in Ruby and are best avoided unless you really need them. If you actually do you could do this:
class Result
@@min = 0
@@max = 0
def self.min
@@min
end
def self.min=(new_min)
@@min = new_min
end
def self.max
@@max
end
def self.max=(new_max)
@@max = new_max
end
def initialize(min, max)
@@min = min
@@max = max
end
def min
@@min
end
def max
@@max
end
end
puts Result.min
puts Result.max
result = Result.new(1, 10)
puts result.min
puts result.max
puts Result.min
puts Result.max
Be warned though, class variables are tricky.
Upvotes: 1