Helpful Information
 
 
Category: Ruby Programming
Making an object initialize to nil

I'm doing an assignment from the Learning Ruby tutorial, and I'm having a bit of a problem. I have a student class that holds a first name, a last name, and an age; pretty generic. Now I figure that should an empty string be given for one of the names, or a value less than zero for the age, then the object should be nil, since there is no apparent logical way to just substitute the invalid values with some generic value. Thing is, I'm not sure how to initialize an object to nil. Here's my failed attempt:

Student class:
class Student
attr_reader :f_name
attr_reader :l_name
attr_reader :age

def initialize(f_name,l_name,age)
if f_name.empty? || f_name == nil || l_name.empty? || l_name == nil || age < 0
return nil
end
@f_name = f_name
@l_name = l_name
@age = age
end

def full_name
return f_name + ' ' + l_name
end
end

TestStudent class:
require 'test/unit'
require 'student'
class TestStudent < Test::Unit::TestCase
def setup
@obj1 = Student.new('Dustin','Pyle',17)
@obj2 = Student.new('','Shulz',12)
@obj3 = Student.new('Jamey','',17)
@obj4 = Student.new('Benny','Rutledge',0)
end

def test_first_name
assert_equal('Dustin',@obj1.f_name)
assert_nil(@obj2)
end

def test_last_name
assert_equal('Pyle',@obj1.l_name)
assert_nil(@obj3)
end

def test_age
assert_equal(17,@obj1.age)
assert_nil(@obj4)
end

def test_full_name
assert_equal('Dustin Pyle',@obj1.full_name)
assert_nil(@obj2)
assert_nil(@obj3)
assert_nil(@obj4)
end
end

The test objects are obviously not initializing to nil since I always get failures. How do I go about this?

new is used to create an object, not to assign it a value. If you look at what Object.new returns it is not a 'value' as you suspect:
irb(main):002:0> class Test
irb(main):003:1> def initialize(val)
irb(main):004:2> nil if val < 0
irb(main):005:2> val
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> Test.new(42)
=> #<Test:0xb7f41a84>
irb(main):009:0>So you have a couple of options, you can make a wrapper to the class and do your checks there

def wrapper(fname,lname,age)
nil || Student.new(...) if not [fname,lname].include? nil and age > 0
endOr a less elegant way is to have a valid 'flag' within the Student class itself
class Student
def initialize(...)
@valid = true if ...
# ...
end
end

Ah, I see. Thanks for the help.










privacy (GDPR)