Readers and Writers
Lesson 28 of 48 in Coddy's Ruby for GDScript Developers course.
GDScript properties can define getters and setters; an underscore in a member name is a convention rather than enforced private access. Ruby attr_reader and attr_accessor generate methods, and custom writers can validate changes. Ruby attribute syntax still invokes methods. A reader alone neither deep-copies its result nor makes a mutable returned object immutable.
GDScript: complete program
extends SceneTree
class Meter:
var _level = 4
func set_level(n):
if n >= 0:
_level = n
func get_level():
return _level
func _init():
var meter = Meter.new()
meter.set_level(-1)
print(meter.get_level())
quit()
Ruby: complete program
class Badge
attr_reader :serial
def initialize(serial)
@serial = serial
end
end
puts Badge.new("Q7").serialChallenge
EasyDefine Box with initialize(width,height), width reader/writer, height reader, and area. Dimensions are positive integers. solve reads width height new_width and returns area before and after assigning width.
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, box.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'box'
def check(value)
raise 'Public API check failed' unless value
end
b = Box.new(7, 3)
check(b.width == 7 && b.height == 3 && b.area == 21)
b.width = 2
check(b.area == 6 && !b.respond_to?(:height=))
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 GDScript Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow 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