See the example below, i suppose it is best to use the second method but the first also works. Which method is best and what are the consquences of using the other ?
class Test
def start
p "started"
end
test = Test.new
test.start
end
class Test2
def start
p "started"
end
end
test2 = Test2.new
test2.start
Ruby on Rails Best Practice: Keep Your Code DRY Ruby on Rails' object-oriented principles are built to help you avoid duplicating code throughout your web application. Whenever possible, a great Ruby on Rails tip is to re-use as much code as possible instead of repeating similar code in many places.
In Ruby, a class is an object that defines a blueprint to create other objects. Classes define which methods are available on any instance of that class. Defining a method inside a class creates an instance method on that class. Any future instance of that class will have that method available.
Re accessing instance/class variables (mainly from the console), for me it worked like FooClass. class_variable_set(:@@foo, 'bar') and FooClass. class_variable_get(:@@foo) , and for instances foo_class. instance_variable_set(:@foo, 'baz') and foo_class.
class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.
I would say definitely the second variant makes much more sense. The first will not cause an error, but the object instantiation is totally obsolete and meaningless. Outside variables are not visible within the class's scope:
var = "string"
class A
var = A.new
end
puts var #=> string
There's no closure, the outer var
is different from that within the class. This means your object "gets lost" after creation and won't be accessible anymore, and eventually be subject to GC.
When you say that the first example "works", working in this context means that it is possible to call a method on a newly created object right after creating that object in the class scope. But it is not possible to hold that object as a reference for later use (without assigning it to class (instance) variables).
If you need no reference for later use, and you really want to do such a "one shot" operation, it would be more idiomatic to either use a class method that can be called without instantiating an object or to do what's necessary in the initialize
, if it's something that has to be done on each instantiation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With