Menu
CoddyTech

Mutation and Aliases

Lesson 21 of 48 in Coddy's Ruby for Java Developers course.

Java reference assignment and Ruby object assignment share referenced mutable objects. Java final prevents reference rebinding, not mutation of the object. Collections.reverse mutates a list; Ruby reverse! mutates whereas reverse creates another array. Immutable Java collection factories should not be used where mutation is the lesson.

Java: complete program

import java.util.*;
public class Main {

  public static void main(String[] args) {
    List<Integer> values = new ArrayList<>(List.of(1, 2, 3));
    List<Integer> alias = values;
    Collections.reverse(values);
    System.out.println(alias.stream().map(Object::toString).collect(java.util.stream.Collectors.joining(" ")));
  }
}

Ruby: complete program

values = [1, 2, 3]
alias_values = values
values.reverse!
puts alias_values.join(" ")
challenge icon

Challenge

Easy

Define cap!(values, ceiling) that replaces values greater than ceiling in the original array and returns the number changed. solve reads ceiling followed by values and returns count|space-separated-values. An empty list produces 0|.

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, limits.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'limits'
def check(value)
  raise 'Public API check failed' unless value
end
v = [9, -2, 9]; alias_v = v
check(cap!(v, 4) == 2)
check(alias_v == [4, -2, 4])
check(cap!(v, 4) == 0)

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 Java Developers

Practice on your own: Online Ruby compiler