In Ruby, what is the difference between putting code in an initialize() method rather than directly in the class body? Both appear to be executed when calling MyClass.new.
Clearly, initialize() can accept parameters, but is that the only difference?
class MyClass
puts 'Hello'
def initialize(params)
puts 'World'
end
end
Try to create two instances of MyClass
to see the difference:
Code in the class body execute only once – when ruby loads the file. initialize() executes every time you create a new instance of your class.