Defining an Uninitialized Instance Variable
source link: https://www.codesd.com/item/defining-an-uninitialized-instance-variable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Defining an Uninitialized Instance Variable
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
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)
Related Articles
Does the naming of an instance variable with the underline title as a prefix have side effects in Cocoa (Objective-C)?
Why can not I directly access the instance variables in the Active Record callback?
Ruby instance variables or local variables?
memoization in rails using an instance variable
Why does the local variable MUST be initialized and why instance variables MUST NOT be initialized before being used?
ARC Memory Management: @Property (nonatomic, strong) VS instance variable
Syntax for C # variables - why do you use the class name twice when defining a new instance?
Is it possible to call defined? on a dynamic instance variable name?
Defining Objective-C private instance variables
If we define our own constructor, how does java initialize the instance variables to their default value?
Define instance variables in Objective-C categories with associative references - Error & ldquo; Using the identifier not declared 'OBJC_ASSOCIATION_RETAIN & rdquo;
Objective-C: Instance variable used while "self" is not defined and hellip; but he is
The instance variable is not defined in Rails 4
How to define a value of a text field if an instance variable is not null in the rails
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK