This question is regarding programming practices in Ruby.
Is it preferable to create instance variables in ruby inside a static method? Or should they be created in an initialize method?
-
3... How would you create instance variables in a class method (in a way that actually made sense to do)?Dave Newton– Dave Newton2013-10-22 18:23:21 +00:00Commented Oct 22, 2013 at 18:23
-
1I don't think there's an accepted "standard practice" regarding the initialization or first use of instance variables. It depends upon the semantics of the variable and how you are using it. I've seen either quite often, depending. Setting it in the initializer implies you have a sensible default value, which may not be the case.lurker– lurker2013-10-22 18:26:17 +00:00Commented Oct 22, 2013 at 18:26
-
Ruby doesn't really have static methods. A similar concept is class methods, but there's no easy or sensible way to manipulate an instance in a class method.Jim Stewart– Jim Stewart2013-10-22 18:28:17 +00:00Commented Oct 22, 2013 at 18:28
-
1I think that @mbranch is right that it's largely a matter of style. Some may want to document all their instance variables in one place, so if some must be in initialize(), they'll stick them all there. Others take the view that one should initialize instance variables in initialize() only when it is necessary to do so (and more generally, to initialize all variables only where it is necessary to do so.) No matter your view, don't straddle these camps--it will be confusing to anyone reading your code, possibly even you. (I'm in the latter camp, btw.)Cary Swoveland– Cary Swoveland2013-10-22 19:08:47 +00:00Commented Oct 22, 2013 at 19:08
Add a comment
|
1 Answer
Well initialize is made for that, why would you do something different.
class SomeClass
def initialize(first, second)
@first = first
@second = second
end
end
3 Comments
lurker
Instance variables are often set in the Rails framework inside methods other than the class initializer. You may have cases where there is no sensible default value to initialize it to and you'd rather have it be
nil until it's needed.Andrea
Thanks @mbratch I'm starting learning Ruby still didn't get into Rails.
Dave Newton
The question isn't about Rails, so that's ok.