I am practicing/learning Ruby using Study Notes from www.ruby-lang.org.
I am working on Validation program taken from Ruby Cookbook, but
unable to run program as is. Please advise where I may have gone
Thanks in advance. JSU
Here’s an example from the Ruby Cookbook,
showing how one can do validation of user’s inputs.
Define default getter methods, but not setter methods.
attr_reader :first, :last
When someone tries to set a first name,
enforce rules about it.
if (first == nil or first.size == 0)
raise ArgumentError.new(‘Everyone must have a first name.’)
first = first.dup
first = first.chr.capitalize
@first = first
When someone tries to set a last name,
# enforce rules about it.
if (last == nil || last.size == 0)
raise ArgumentError.new(‘Everyone must have a last name.’)
last = last.chr.capitalize
@last = last
Delegate to the setter methods instead of
# setting the instance variables directly.
def initialize(first, last)
self.first = first
self.last = last
jacob = Name.new(‘Jacob’, ‘Berendes’)
jacob.first = ‘Mary Sue’
jacob.full_name # => “Mary Sue Berendes”
john = Name.new(‘John’, ‘Von Neumann’)
john.full_name # “John Von Neumann”
john.first = ‘john’
john.first # => “john”
john.first = nil
ArgumentError: Everyone must have a first name.
Name.new(‘Kero, international football star and performance artist’,
ArgumentError: Everyone must have a last name.
And my output is as follows:
p050inputvalidation.rb:11:in `first=’: Everyone must have a first
Exit code: 1