August 16th, 2007, 07:55 PM
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:
if f_name.empty? || f_name == nil || l_name.empty? || l_name == nil || age < 0
@f_name = f_name
@l_name = l_name
@age = age
return f_name + ' ' + l_name
class TestStudent < Test::Unit::TestCase
@obj1 = Student.new('Dustin','Pyle',17)
@obj2 = Student.new('','Shulz',12)
@obj3 = Student.new('Jamey','',17)
@obj4 = Student.new('Benny','Rutledge',0)
The test objects are obviously not initializing to nil since I always get failures. How do I go about this?
August 17th, 2007, 07:42 AM
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:
So you have a couple of options, you can make a wrapper to the class and do your checks there
irb(main):002:0> class Test
irb(main):003:1> def initialize(val)
irb(main):004:2> nil if val < 0
Or a less elegant way is to have a valid 'flag' within the Student class itself
nil || Student.new(...) if not [fname,lname].include? nil and age > 0
@valid = true if ...
True happiness is not getting what you want, it's wanting what you've already got.
August 17th, 2007, 04:56 PM
Ah, I see. Thanks for the help.