Menu
CoddyTech

Readers and Writers

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

C can hide an opaque struct behind module functions, while a visible struct exposes its fields directly. Ruby attr_reader and attr_accessor generate methods for common access patterns. A custom writer can validate updates because attribute assignment calls a method. A reader alone does not promise a deep copy or make the returned object immutable.

C: complete program

#include <stdio.h>
struct Meter{int level;};
static void meter_set(struct Meter *m,int level){if(level>=0)m->level=level;}
static int meter_get(const struct Meter *m){return m->level;}

int main(void) {
struct Meter m={4};meter_set(&m,-1);printf("%d\n",meter_get(&m));
return 0;
}

Ruby: complete program

class Badge
  attr_reader :serial
  def initialize(serial)
    @serial = serial
  end
end
puts Badge.new("Q7").serial
challenge icon

Challenge

Easy

Define 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)
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