Reputation:
Is it elegant to use instance variables in a class which are not initialized and setting them using other methods? Or maybe there is a better way to do that?
class Klass
def initialize(a)
@a = a
end
def set_b(b)
@b = b
end
end
Upvotes: 2
Views: 116
Reputation: 2916
In contrast to other languages, If you do not initialize an instance variable it will always be nil
(whereas in certain other languages you could get something undefined).
As long as other methods of Klass
do not depend on the instance variable actually having a value, this should be ok.
As for getters and setters, there are attr_accessor
, attr_reader
and attr_writer
(see the docs).
class Klass
attr_accessor :b
# there's also attr_reader and attr_writer
def initialize(a)
@a = a
end
end
k = Klass.new :foo
k.b = :bar
k.b
#=> :bar
k.a
#=> undefined method `a' for #<Klass:0x007f842a17c0e0 @a=:foo, @b=:bar> (NoMethodError)
Upvotes: 1
Reputation: 8066
The way you are doing it works but Ruby defined attr_accessor
, attr_reader
and attr_writer
for that purpose.
attr_reader
: create method to read 'a'
attr_writer
: create method to write 'a'
attr_accessor
: create methods to read and write 'a'
I think the best way to do that is to use attr_accessor:a
class Klass
attr_accessor:a
def initialize(a)
@a = a
end
end
Then you can do:
k = Klass.new "foo" #example
k.a = "bar"
Upvotes: 0