On Wed, Dec 21, 2005 at 10:57:01AM +0900, Jeff Cohen wrote:
> Switching from C# to Ruby, and learning to write "the Ruby way"... is 
> there a better way to get the first and last names from a string?
> 
> Assume for simplicity that the the first name is the text up to the 
> first space, and the last name is the text after the last space.
> 
> def split_name(fullname)
> 	parts = fullname.split(' ')
> 	[parts.first, parts.last]
> end
> 
> This returns me an array so I can do this:
> 
> first, last = split_name("Donald P. Q. Duck")
> 
> first => "Donald"
> last => "Duck"
> 
> (man, I love Ruby).
> 
> But something about split_name still feels a bit "wrong", like there's a 
> more succint Ruby way to return the first and last elements of the 
> split() results.

In Ruby you can open up any class and modify/extend it at any time. Even the
built in ones. So you could do:

  class String
    def name_parts(pattern = ' ', limit = 2)
      split(pattern, limit)
    end
  end

  'Marcel Molina Jr.'.name_parts
  => ["Marcel", "Molina Jr."]

marcel
-- 
Marcel Molina Jr. <marcel / vernix.org>