Menu
CoddyTech

Classes and Instances

Lesson 27 of 48 in Coddy's Ruby for C Developers course.

C structs declare a layout, and helper functions receive a record or pointer explicitly. Ruby new invokes initialize and stores per-object values in at-sign instance variables without static field declarations. Each instance can retain independent state. C factory functions can initialize records, but C has no automatic Ruby-style constructor or bound method protocol.

C: complete program

#include <stdio.h>
struct Item { int n; };
static struct Item item_new(int n)
{
    struct Item item = {n};
    return item;
}
int main(void)
{
    struct Item a = item_new(2);
    struct Item b = item_new(5);
    a.n = 8;
    printf("%d:%d\n", a.n, b.n);
    return 0;
}

Ruby: complete program

class Greeting
  def initialize(word)
    @word = word
  end
  def text
    @word.upcase
  end
end
puts Greeting.new("hi").text
challenge icon

Challenge

Easy

Define 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C Developers

Practice on your own: Online Ruby compiler