Chris Roos
5/5/2005 11:57:00 PM
David A. Black wrote:
> Hi --
>
> On Fri, 6 May 2005, Chris Roos wrote:
>
>> I have a Person with title, forename and surname (all of which are
>> optional). I want to return a 'pretty' name for this person in the
>> format..
>>
>> title + <space> + forename + <space> + surname
>>
>> ..where any extraneous spaces are removed.
>>
>> My name method currently looks like this
>>
>> def name
>> (
>> (title.to_s.strip.empty? ? "" : title.to_s.strip << " ") <<
>> (forename.to_s.strip.empty? ? "" : forename.to_s.strip << " ") <<
>> (surname.to_s.strip.empty? ? "" : surname.to_s.strip)
>> ).strip
>> end
>>
> [...]
>
>> What I was originally going to ask was how to improve on the first
>> implementation above. Even though (in my opinion) the second
>> implementation is a lot cleaner I'm still interested in whether it can
>> be made even more succinct as in 'the ruby way'?
>
>
> I'd let Ruby do more of the work, especially the iterating through the
> items. Something like this might be suitable:
>
> class Person
> attr_accessor :title, :forename, :surname
> def name
> [title, forename, surname].compact.map {|s| s.strip }.join(" ")
> end
> end
>
>
> David
>
Hmm, an hours work and a five line implementation replaced by one line a
matter of minutes... I have a long way to go ;-)
Thanks for your help.