From: Josh Cheek Date: 2011-10-11T12:27:51+09:00 Subject: Re: Basic OO Class question --bcaec51d22eef14ee204aefd7d4e Content-Type: text/plain; charset=ISO-8859-1 On Mon, Oct 10, 2011 at 3:55 AM, Robert Klemme wrote: > 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. > > Interesting, I like it. I usually only dup data if I find I need it, but for lib code it probably makes sense to be more proactive. I'm a bit ambivalent about to_int, though, I suppose it depends on the situation. --bcaec51d22eef14ee204aefd7d4e--