Menu
CoddyTech

读取器与写入器

Coddy 面向 C 开发者的 Ruby 课程的第 28 课,共 48 课。

C 可以通过模块函数隐藏不透明结构体,而可见结构体会直接公开其字段。Ruby 的 attr_reader 和 attr_accessor 会为常见的访问模式生成方法。由于属性赋值会调用方法,因此可以通过自定义写入器验证更新。仅有读取器并不保证会进行深拷贝,也不会使返回的对象不可变。

C:完整程序

#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:完整程序

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

挑战

简单

定义 Box,包含 initialize(width,height)、可读写的 width、只读的 height,以及 area。尺寸是正整数。solve 读取 width、height 和 new_width,并返回赋值 width 前后的面积。

从 solve(input) 返回文本,不要打印。锁定的驱动程序会用一个末尾换行符打印返回的文本,并独立检查所需的公共 API。

你的代码写在 exercise.rb 和 box.rb 中。main.rb 包含提供的输入/输出代码,不能修改。

亲手试试

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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器