This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
Validating and Modifying Attribute Values | ||
---|---|---|
Code | Expected | Actual |
class Name # Define default getter methods, but not setter methods. attr_reader :first, :last # When someone tries to set a first name, enforce rules about it. def first=(first) if first == nil or first.size == 0 raise ArgumentError.new('Everyone must have a first name.') end first = first.dup first[0] = first[0].chr.capitalize @first = first end # When someone tries to set a last name, enforce rules about it. def last=(last) if last == nil or last.size == 0 raise ArgumentError.new('Everyone must have a last name.') end @last = last end def full_name "#{@first} #{@last}" end # Delegate to the setter methods instead of setting the instance # variables directly. def initialize(first, last) self.first = first self.last = last end end jacob = Name.new('Jacob', 'Berendes') jacob.first = 'Mary Sue' jacob.full_name |
"Mary Sue Berendes" | "Mary Sue Berendes" |
john = Name.new('john', 'von Neumann') john.full_name |
"John von Neumann" | "John von Neumann" |
john.first = 'john' john.first |
"John" | "John" |
john.first = nil |
ArgumentError: Everyone must have a first name. ... |
ArgumentError: Everyone must have a first name. from (irb):7:in `first=' from (irb):37 |
Name.new('Kero, international football star and performance artist', nil) |
ArgumentError: Everyone must have a last name. ... |
ArgumentError: Everyone must have a last name. from (irb):16:in `last=' from (irb):27:in `initialize' from (irb):38 |
class SimpleContainer attr_accessor :value end c = SimpleContainer.new c.respond_to? "value=" |
true | true |
c.value = 10; c.value |
10 | 10 |
c.value = "some random value"; c.value |
"some random value" | "some random value" |
c.value = [nil, nil, nil]; c.value |
[nil, nil, nil] | [nil, nil, nil] |