Ruby:initialize() 与类体? [英] Ruby: initialize() vs class body?

查看:39
本文介绍了Ruby:initialize() 与类体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,将代码放在 initialize() 方法中而不是直接放在类体中有什么区别?两者似乎在调用 MyClass.new 时都被执行.

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.

显然,initialize() 可以接受参数,但仅此而已吗?

Clearly, initialize() can accept parameters, but is that the only difference?

class MyClass
  puts 'Hello'

  def initialize(params)
    puts 'World'
  end
end

推荐答案

尝试创建 MyClass 的两个实例

Try to create two instances of MyClass

a = MyClass.new
b = MyClass.new

看看区别:

你好

世界

世界

类体中的代码只执行一次 - 当 ruby​​ 加载文件时.initialize() 每次创建类的新实例时都会执行.

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.

这篇关于Ruby:initialize() 与类体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆