freeze
method in the Object
class protects an object from changes, turning it into a constant. After the object is “frozen”, any attempt to change it will turn into a TypeError error. Method frozen?
will let you know if the object is frozen:a = b = 'Original String'
b.freeze
puts a.frozen? # true
puts b.frozen? # true
a = 'New String'
puts a
puts b
puts a.frozen? # false
puts b.frozen? # true
a
and b
first refer to one object, so true
in the first two cases.Java
, it is possible to serialize objects, allowing you to save them in binary form to a file and extract them as needed. Ruby calls this type of serialization marshaling (marshaling), using the Marshal
built-in library. The main methods are dump
and load
: f = File.open( 'peoples.sav', 'w' ) Marshal.dump( ["bred", "bert", "kate"], f ) f.close File.open( 'peoples2.sav', 'w' ){ |friendsfile| Marshal.dump( ["anny", "agnes", "john" ], friendsfile ) } myfriends = Marshal.load(File.open('peoples.sav' )) morefriends = Marshal.load(File.open('peoples2.sav' )) puts myfriends puts morefriends
Marshal
, the YAML
library allows you to save data in text format, about it some other time.module
used instead of class
. Unlike classes, it is impossible to create objects based on a module; a module cannot have subclasses. Instead, you add the missing functionality of a class or individual object using a module. Modules - single, no hierarchy and inheritance. (In general, the Module
class has a superclass - Object
, but any created module of the superclass has no). module Trig PI = 3.1416 # def Trig.sin(x) # ... end def Trig.cos(x) # ... end end
module MyModule GOODMOOD = "happy" BADMOOD = "grumpy" def greet return "I'm #{GOODMOOD}. How are you?" end def MyModule.greet return "I'm #{BADMOOD}. How are you?" end end class MyClass include MyModule def sayHi puts( greet ) end end ob = MyClass.new ob.sayHi puts(ob.greet)
mixin
's.Source: https://habr.com/ru/post/49353/
All Articles