Class TShirt
def size(suggested_size)
if suggested_size == nil
size = "please choose a size"
else
size = suggested_size
end
end
end
tshirt = TShirt.new
tshirt.size("M")
== "M"
tshirt = TShirt.new
tshirt.size(nil)
== "please choose a size"
What is a better way to have optional objects in a method? Procs?
Default values may be what you’re looking for:
You can find some more information about default values over at wikibooks. They also go over variable length argument lists and the option of passing in a hash of options to the method, both of which you can see in a lot of Rails code…
Variable Argument List
File vendor/rails/activerecord/lib/active_record/base.rb, line 607:
Options Hash
File vendor/rails/activerecord/lib/active_record/base.rb, line 1361:
Object Attributes
If you are looking to have optional attributes in an object, you can write a getter and setter method in your class:
Then you could just call use tshirt.size=”xl” and tshirt.size on an instance of your TShirt class.