Syntax error in Ruby Cookbook example

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
wrong.
Thanks in advance. JSU

p050inputvalidation.rb

Here’s an example from the Ruby Cookbook,

showing how one can do validation of user’s inputs.

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 || last.size == 0)
raise ArgumentError.new(‘Everyone must have a last name.’)
end
last[0] = last[0].chr.capitalize
@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”
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’,
nil)

ArgumentError: Everyone must have a last name.

And my output is as follows:

ruby p050inputvalidation.rb
p050inputvalidation.rb:11:in `first=’: Everyone must have a first
name. (ArgumentError)
from p050inputvalidation.rb:46
Exit code: 1

Thanks again!

Am Mittwoch 17 Juni 2009 00:00:05 schrieb JSU:

I am working on Validation program taken from Ruby Cookbook, but
unable to run program as is.

From what you’ve pasted it seems like you’re getting exactly the result
that
the comments indicate you should be getting, so I don’t see a problem
there.
If you look at the comments, you’ll notice that some of those lines are
supposed to cause Exceptions.

HTH,
Sebastian

On Jun 16, 4:30 pm, Sebastian H. [email protected]
wrote:

HTH,
Sebastian

Thanks Sebastian. I suppose I was thrown because it doesn’t look all
tidy like the other examples. Cheers. JSU