From: Dark Ambient Date: 2006-08-11T23:19:51+09:00 Subject: Re: Question on setting up a class and searching on objects James, Thank you for the explanation and example. Ran through you code in irb so the next step is implementing my method for a search function. Hopefully I will only be back to say I've figured it out. No help for now though. Stuart On 8/11/06, James Edward Gray II wrote: > On Aug 11, 2006, at 7:47 AM, Dark Ambient wrote: > > > I'm working from Ruby for Rails book but want to try and just > > replicate some of the examples in Ruby alone. > > One method in particular is called whole_name and would give the user > > the ability to search a list by first_name, middle_name, or last_name. > > If you want to make a method to search the the individual composers, > you will need to get them into some data structure (like an Array) > where you can scan through them. > > > class Composer > > > > def listcomp (first_name, middle_name, last_name) > > f = first_name > > m = middle_name > > l = last_name > > end > > What are you intending this method to do? Currently, it doesn't do > anything meaningful: > > 1. first_name, middle_name, and last_name are accepted as arguments > 2. Each of those is assigned to another local variable > 3. All six local variables are discarded as the method exits > > > def whole_name > > first_name + " " + > > (if middle_name then middle_name + " " else "" end) + > > last_name > > end > > end > > This method doesn't work because it uses local variables that don't > exist in this method. I believe this is your hang-up. > > Inside a class, you keep data around by putting it into instance > variables (those start with an @ symbol). All methods of the class > can access the instance variables for the current object. > > See if this helps explain things: > > >> class Name > >> def initialize(first, last, middle = nil) > >> # assign these local variables to instance variables... > ?> @first = first > >> @last = last > >> @middle = middle > >> end > >> > ?> # create methods to read those instance variables... > ?> attr_reader :first, :last, :middle > >> > ?> def full > >> [@first, @middle, @last].join(" ").squeeze(" ") > >> end > >> end > => nil > >> james = Name.new("James", "Gray", "Edward") > => # > >> james.last > => "Gray" > >> james.full > => "James Edward Gray" > >> dana = Name.new("Dana", "Gray") > => # > >> dana.middle > => nil > >> dana.full > => "Dana Gray" >