Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

Ruby: initialize() vs class body?

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
question from:https://stackoverflow.com/questions/6043618/ruby-initialize-vs-class-body

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try to create two instances of MyClass

a = MyClass.new
b = MyClass.new

to see the difference:

Hello

World

World

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...