From: Robert Klemme Date: 2011-10-10T17:55:40+09:00 Subject: Re: Basic OO Class question On Mon, Oct 10, 2011 at 2:53 AM, Josh Cheek wrote: > On Sun, Oct 9, 2011 at 5:44 PM, Kevin E. wrote: > >> Hi All >> >> I am try to get up to speed on several things at once; namely, OO and >> also Ruby.  I have written a bunch or Ruby scripts to perform various >> text processing tasks but I think I want to start learning something >> about OO Programming.  I do have the book "Programming Ruby" and it is a >> great help. >> >> My question is related to writing a class for something like a polygon. >> It can be described by a few integer and string properties. So I could >> do something like this snippet: >> >> class Zone >> >>    attr_accessor :type, :length >> >>    def initialize(type, length) >>      @type = type >>      @length = length >>    end >> >> end >> >> testZ = Zone.new("Rad", 20.1) >> >> Here is what I don't know how to do.  How do I add an array of integers >> to this class?  It would need to be of variable length. > Give it an accessor and then initialize the associated instance variable to > an array. > > > class Zone > >  attr_accessor :type, :length, :integers > >  def initialize(type, length) >    @type = type >    @length = length >    @integers = Array.new >  end > > end > > test_z = Zone.new("Rad", 20.1) > test_z.integers # => [] > test_z.integers << 1 > test_z.integers # => [1] > test_z.integers << 2 > test_z.integers # => [1, 2] > > > In terms of the integers part, you can't specify the array should contain > integers, I've named it integers to indicate that's what it is, but really > you could put anything in there. That's one of the reasons why I sometimes prefer a more robust approach class Zone attr_accessor :type, :length def initialize(type, length) @type = type @length = length @integers = [] # same as Array.new end def add(an_int) @integers << an_int.to_int self end def integers @integers.dup end end This does two things: 1. ensure that only integers are put into the array by doing conversion #to_int. 2. copies the array on access to avoid someone outside the instance to mess with internal state. Whether this added robustness is needed depends on the application. You like also have to add methods for removing entries again etc. Kevin: Btw, what is the "type" member supposed to mean? If that should control behavior in some way then strategy pattern (or a similar one) would be a better solution. http://en.wikipedia.org/wiki/Strategy_pattern http://www.oodesign.com/strategy-pattern.html http://c2.com/cgi/wiki?StrategyPattern 2nd note: if @length should represent the length of the Array you do not need a separate member. Instead you can do def length @integers.length # or .size end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/