From: Heesob Park Date: 2008-05-03T10:08:19+09:00 Subject: Re: How to access to an Array element without doing "find" each time Hi, I単aki Baz Castillo wrote: > Hi, I've an Array containing complex objects of Header class: > > ------------------------------------- > class Header > #attributes: > # - @name > # - @original_value > # - @parsed_value > # ... > end > > class Message > #attributes: > # - @first_line > # - @headers = > # [header_1, header_2, header_3...] > # - @body > end > ------------------------------------- > > Just some headers are parsed, and for a header "From", @name attribute > can be: > "From", "from", "FROM", "F", "f" ... => /^(from|f)$/i > > > Now I need to access a specifi header ("From" for example) several times > and I > want to avoid doing a "Header.find { |h| h.name =~ /^(from|f)$/i }" for > each > access,so: > > class Message > def header(name) > Header.find { |h| h.name =~ /^(from|f)$/i } > end > end > > > But doing message.header("From") for each access will be not very > efficient > and I try to avoid it. Is there any other way? > > I could doing an assigment just the first time: > > message.hdr_from = message.header("From") > ...do_somethig_with_hdr_from... : > message.hdr_from.parsed_value.uri > message.hdr_from.parsed_value.uri.name > message.hdr_from.parsed_value.display_name > ... > > So "hdr_from" is like a pointer to header("From"), but it's not valid > for me > since I need the possibility of doing a re-assignement: > > header("From") = header("To") > > So if after doing that I use "message.hdr_from" I will access to the > previous > value of "From" header instead of the new one. > > > In fact, what I'm looking for is a persister pointer, concept that I > already > know doesn't exist in Ruby :( > How about use class variable something like this: class Message def initialize @@header = {} end def header(name) return @@header[name] ||= @headers.find { |h| h.name =~ /^(from|f)$/i } end end > Thanks for any suggestion. Regards, Park Heesob -- Posted via http://www.ruby-forum.com/.