Mutation and Aliases
Lesson 21 of 48 in Coddy's Ruby for Lua Developers course.
Lua table assignment and Ruby array assignment share the referenced mutable object. Lua strings remain immutable, unlike ordinary Ruby strings. Ruby method names ending in an exclamation mark often indicate a destructive alternative, but many mutators have no such suffix. The Lua example explicitly swaps endpoints to demonstrate mutation visible through an alias.
Lua: complete program
local values = {1, 2, 3}
local alias = values
values[1], values[3] = values[3], values[1]
print(table.concat(alias, " "))Ruby: complete program
values = [1, 2, 3]
alias_values = values
values.reverse!
puts alias_values.join(" ")Challenge
EasyDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Lua 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 Ratio2Flow 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