ruby 新建对象_Ruby中的冻结对象

╰半橙微兮° 2023-03-05 09:46 147阅读 0赞

ruby 新建对象

Ruby| 冻结物体 (Ruby | Frozen objects)

Freezing objects or instances in Ruby means that we are disallowing them to get modified in the future. You can understand this in a way that you can’t change their instance variables, you can’t provide singleton methods to it as well as if we are freezing a class or a module, and you can’t add, remove and bring some changes in its methods.

在Ruby中冻结对象或实例意味着我们不允许将来对其进行修改。 您可以这样一种方式来理解它:您不能更改其实例变量,不能向其提供单例方法,也不能冻结我们的类或模块,也不能添加,删除和带入某些变量。方法的变化。

How to freeze objects in Ruby?

如何在Ruby中冻结对象?

You can freeze objects in Ruby by in invoking freeze method which is a method defined in Object Class in Ruby’s library. There is no method to unfreeze the object which is once frozen.

您可以通过调用Frozen方法冻结Ruby中的对象,该方法是Ruby库中Object Class中定义的方法。 没有方法可以解冻一旦冻结的对象。

Syntax:

句法:

  1. Object_name.freeze

How to check whether the object is frozen or not?

如何检查物体是否冻结?

There is a very simple way to check whether the object is frozen or not. You only have to invoke frozen? method of Object class. If the method returns true then the object is frozen otherwise not.

有一种非常简单的方法来检查对象是否冻结。 您只需要调用冻结? Object类的方法 。 如果该方法返回true,则将冻结对象,否则不会冻结。

Syntax:

句法:

  1. Object_name.frozen?

Program:

程序:

  1. =begin
  2. Ruby program to demonstrate frozen objects
  3. =end
  4. class Multiply
  5. def initialize(num1,num2)
  6. @f_no = num1
  7. @s_no = num2
  8. end
  9. def getnum1
  10. @f_no
  11. end
  12. def getnum1
  13. @s_no
  14. end
  15. def setnum1=(value)
  16. @f_no = value
  17. end
  18. def setnum2=(value)
  19. @s_no = value
  20. end
  21. end
  22. mul = Multiply.new(23,34)
  23. mul.freeze
  24. if(mul.frozen?)
  25. puts "mul is frozen object"
  26. else
  27. puts "mul is not frozen object"
  28. end
  29. mul.setnum2=12
  30. mul.setnum1=13
  31. puts "Y is #{mul.getnum1()}"
  32. puts "Z is #{mul.getnum2()}"

Output

输出量

  1. mul is frozen object
  2. can't modify frozen Multiply
  3. (repl):20:in `setnum2='
  4. (repl):33:in `<main>'

Explanation:

说明:

In the above code, you can observe that we have frozen the object mul with the help of Object.freeze method. We are getting an error known as FrozenError because we are trying to bring changes in the variables of the frozen object with the help of some other methods. We know that we can’t bring any change in the variables of the object which is frozen.

在上面的代码中,您可以观察到我们已经借助Object.freeze方法冻结了对象mul 。 我们收到一个称为FrozenError的错误,因为我们试图借助其他一些方法来更改冻结对象的变量。 我们知道,冻结的对象的变量无法带来任何变化。

翻译自: https://www.includehelp.com/ruby/frozen-objects-in-ruby.aspx

ruby 新建对象

发表评论

表情:
评论列表 (有 0 条评论,147人围观)

还没有评论,来说两句吧...

相关阅读