Say I have:
class Cell
def initialize(x_var, y_var)
x = x_var
y = y_var
end
end
How would I be able to access the variables of the object cell?
cell1 = Cell.new(0, 0)
x = cell1.x
y = cell1.y
Is this correct?
Say I have:
class Cell
def initialize(x_var, y_var)
x = x_var
y = y_var
end
end
How would I be able to access the variables of the object cell?
cell1 = Cell.new(0, 0)
x = cell1.x
y = cell1.y
Is this correct?
There are a few things for you to learn:
1- Variable's scope
class Cell
def initialize(x_var, y_var)
x = x_var
y = y_var
end
def print_x
puts x
end
end
Cell.new(1,1).print_x
You get the following:
NameError: undefined local variable or method `x' for #<Cell:0x007ff901d9f448>
In the code above, the variable x
gets "lives" between def initialize
and end
. This is the scope of x
. If you try to access x
outside that scope, you'd get a NameError
telling you it's not defined.
2- Now, if you want a variable that lives as long as the object does, you can use instance variables
. Instance variables start with an @
and live as long as the object does.
class Cell
def initialize(x_var, y_var)
@x = x_var
@y = y_var
end
def x
return @x
end
def x=(val)
@x = val
end
def y
return @y
end
def y=(val)
@y = val
end
end
c = Cell.new(1,2)
puts c.x
Gives the following:
1
=> nil
3- You had to write too much code in my example above to achieve very little. This is where @aruprakshit's attr_reader
comes handy:
attr_reader :x
generates the method:
def x
return @x
end
4- If you want to read and write to @x
, i.e., generate both the x
and x=
methods, attr_accessor
does that for you:
class Cell
attr_accessor :x, :y
def initialize(x_var, y_var)
@x = x_var
@y = y_var
end
end
c = Cell.new(1,2)
puts c.x
c.x = 3
puts c.x
Gives the following:
1
=> nil
=> 3
3
=> nil
How would I be able to access the variables of the object cell?
You need to look into attr_reader
for this purpose.
class Cell
attr_reader :x,:y
def initialize(x_var, y_var)
@x = x_var
@y = y_var
end
end
cell1 = Cell.new(0, 0)
cell1.x # => 0
cell1.y # => 0
Read this Why use Ruby's attr_accessor, attr_reader and attr_writer?
to know about attr_reader.