B
Bharat Ruparel
I have been reading The Ruby Programming Language book by David Flanagan
and Matz. It is written quite well. Some examples are not clear (to
me): Here is one from Chapter 7 page 244 which defines a class to set
enumerated types:
class Season
NAMES = %w{ Spring Summer Autumn Winter } # Array of season names
INSTANCES = [] # Array of Season objects
def initialize(n) # The state of a season is just its
@n = n # index in the NAMES and INSTANCES arrays
end
def to_s # Return the name of a season
NAMES[@n]
end
# This code creates instances of this class to represent the seasons
# and defines constants to refer to those instances.
# Note that we must do this after initialize is defined.
NAMES.each_with_index do |name,index|
instance = new(index) # Create a new instance
INSTANCES[index] = instance # Save it in an array of instances
const_set name, instance # Define a constant to refer to it
end
# Now that we have created all the instances we'll ever need, we must
# prevent any other instances from being created
private_class_method :new,:allocate # Make the factory methods
private
private :dup, :clone # Make copying methods private
end
My question is how do you use this class from the client code? Can
someone give some examples?
Thanks.
Bharat
and Matz. It is written quite well. Some examples are not clear (to
me): Here is one from Chapter 7 page 244 which defines a class to set
enumerated types:
class Season
NAMES = %w{ Spring Summer Autumn Winter } # Array of season names
INSTANCES = [] # Array of Season objects
def initialize(n) # The state of a season is just its
@n = n # index in the NAMES and INSTANCES arrays
end
def to_s # Return the name of a season
NAMES[@n]
end
# This code creates instances of this class to represent the seasons
# and defines constants to refer to those instances.
# Note that we must do this after initialize is defined.
NAMES.each_with_index do |name,index|
instance = new(index) # Create a new instance
INSTANCES[index] = instance # Save it in an array of instances
const_set name, instance # Define a constant to refer to it
end
# Now that we have created all the instances we'll ever need, we must
# prevent any other instances from being created
private_class_method :new,:allocate # Make the factory methods
private
private :dup, :clone # Make copying methods private
end
My question is how do you use this class from the client code? Can
someone give some examples?
Thanks.
Bharat