I see code like:
class Person
def initialize(name)
@name = name
end
end
I understand this allows me to do things like person = Pe
Unlike C++,Java instance variables in Ruby are private by default(partially as they can be accessed by using a.instance_variable_get :@x)
eg:
class Dda
def initialize task
@task = task
@done = false
end
end
item = Dda.new "Jogging" # This would call the initializer and task = Jogging would
be set for item
item.task # would give error as their is no function named task to access the instance
variable.
Although we have set the value to item but we won't be able to do anything with it as instace variables are private in ruby. code for getter:
def task
@task
end
#for getter
def task=task
@task = task
end
Using getter would ensure that item.task returns it's value And using setter gives us the flexibility to provide values to instance variables at any time.