Classes and Instances
Lesson 27 of 48 in Coddy's Ruby for GDScript Developers course.
GDScript new invokes _init, while Ruby new invokes initialize. GDScript can declare typed members; Ruby at-sign instance variables need no field-type declarations. Each instance has its own member storage, but members can refer to shared arrays or collaborators. Godot Node lifetimes and RefCounted ownership differ from ordinary Ruby object lifetime, so do not carry engine cleanup assumptions into these Ruby classes.
GDScript: complete program
extends SceneTree
class Counter:
var n
func _init(initial):
n = initial
func _init():
var first = Counter.new(4)
var second = Counter.new(7)
first.n = 9
print(str(first.n) + ":" + str(second.n))
quit()Ruby: complete program
class Greeting
def initialize(word)
@word = word
end
def text
@word.upcase
end
end
puts Greeting.new("hi").textChallenge
EasyDefine Counter with initialize(start), value and add(amount). add changes only that instance and returns its new value. solve reads a start followed by additions and returns the final value.
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, counter.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'counter'
def check(value)
raise 'Public API check failed' unless value
end
a = Counter.new(4); b = Counter.new(-2)
check(a.add(3) == 7 && a.value == 7 && b.value == -2)
check(b.add(9) == 7 && a.value == 7)
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