Menu
CoddyTech

Copies and Frozen Values

Lesson 38 of 48 in Coddy's Ruby for C# Developers course.

Copying a C# List creates new outer storage but retains references to class-valued elements. Ruby dup is similarly shallow for nested objects. Ruby freeze prevents mutation of that receiver rather than recursively freezing every child. C# readonly fields restrict assignment and also do not imply an immutable object graph.

C#: complete program

using System;
using System.Collections.Generic;
using System.Linq;
var a=new List<List<int>>{new List<int>{1}};var b=new List<List<int>>(a);b[0].Add(2);
Console.WriteLine(string.Join(" ",a[0]));

Ruby: complete program

a = [[1]]
b = a.dup
b[0] << 2
puts a[0].join(" ")
challenge icon

Challenge

Easy

Define Snapshot(values), making a shallow copy of the supplied integer array and freezing that copy. values returns that frozen array. solve reads integers, takes snapshot, then appends 99 to original; output snapshot size and original size.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, snapshot.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'snapshot'
def check(value)
  raise 'Public API check failed' unless value
end
v = [2, 9]; s = Snapshot.new(v); v[0] = 7
check(s.values == [2, 9] && s.values.frozen? && !v.frozen?)

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C# Developers

Practice on your own: Online Ruby compiler