Object Manipulations in Ruby

Ruby allows you to freeze objects and stop you from being able to modify it. However, values are modifiable. Example of such freeze is as following.

my_array = [[1,2],[2,3]].freeze
my_array << [4,5] //produces an error specifying that frozen array can be modified
my_array[1]<<3 //will add new value to first array [1,2,3] without problems.

Frozen objects can be useful for multithreaded code or in preventing future modifications to a frozen class.

Ruby allows to make a copy of the existing object by calling Object.clone method on it.

my_string = “test string”
my_string2 = my_string.clone

In addition to clone, Ruby language has Object.dup method for copying objects. The difference between the two is in a way copy is made. Clone makes a copy of the metaclass and instantiate actual copy instead of instantiating the original class. As a result, you may use dup if you want to make unfrozen copy of a frozen object. Both of these methods create shallow copy, so that you may end up with two objects whose instances point to the same instance variables.

Example of this is presented below

class MyClass
 attr_reader :string
 def initialize(string)
  @string = string
 end
end

my_string1 = MyClass.new(‘String’)/
my_string2 = my_string1.dup
my_strgin3 = my_string1.clone

my_string1.string[0] = ‘Z’
my_string2 and my_string3 will print out Ztring.. so you can see how this can be dangers if caution is not applied with both of these methods.

Please note that cloning or duplicating will not run initialize code for each instantiated object. In order to do that you’ll need to add initialize_copy method.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…