Reputation: 22889
In some languages, you can access attributes of an object without writing your own getter/setter methods.
Do objects have built in getter/setter with Ruby?
Here is what I'm trying:
class Obj
def initialize(color)
@color = color
end
end
t = Obj.new("red")
puts t.color
Upvotes: 1
Views: 678
Reputation: 22889
I found that these methods seem to exist for all objects in Ruby:
t.instance_variable_set(:@color, "blue")
t.instance_variable_get(:@color)
Upvotes: 0
Reputation: 11050
You're looking for attr_accessor :color
if you want just the run of the mill auto-generated getters/setters.
Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute. String arguments are converted to symbols.
There's also just an attr_reader :color
if you don't want to be able to set the value outside the class
Creates instance variables and corresponding methods that return the value of each instance variable.
And attr_writer :color
if you want to set, but not read, outside of the class.
Creates an accessor method to allow assignment to the attribute.
class Obj
attr_accessor :color
def initialize(color)
@color = color
end
end
t = Obj.new("red")
t.color #=> "red"
Upvotes: 7