Copies and Frozen Values
Lesson 38 of 48 in Coddy's Ruby for Java Developers course.
A Java collection copy constructor creates a new outer collection but normally shares its elements. Ruby dup is similarly shallow. Java unmodifiable wrappers, immutable collection factories and Ruby freeze have different details, but none should be assumed to recursively freeze arbitrary child objects. Ownership depth remains an explicit design decision.
Java: complete program
import java.util.*;
public class Main {
public static void main(String[] args) {
List<List<Integer>> a = new ArrayList<>();
a.add(new ArrayList<>(List.of(1)));
List<List<Integer>> b = new ArrayList<>(a);
b.get(0).add(2);
System.out.println(a.get(0).stream().map(Object::toString).collect(java.util.stream.Collectors.joining(" ")));
}
}Ruby: complete program
a = [[1]]
b = a.dup
b[0] << 2
puts a[0].join(" ")Challenge
EasyDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Java Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio7Objects in Practice
Ordering with ComparableCopies and Frozen ValuesLambdas and Captured StateCustom EnumerableRecap: Callable FilterRecap: Limited Store2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler