Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating name helper, to split first and last names apart

I'm looking for some help on how to take an attribute and process it through a method to return something different. But I've never done this before and I' not sure where to start. I thought trying to change a name:string attribute from "George Washington" or "John Quincy Adams" into first names only "George" and "John".

I thought maybe a helper method would be best, such as

users_helper.rb

def first_name

end

and then call @user.name.first_name, would this be initially how it would work? Can someone explain where I'd go next to be able to pass @user.name into the method? I've seen things like this but don't quite understand it the parenthesis...

def first_name(name)
  puts name
end

Could someone breakdown how rails/ruby does this type of thing? Thanks a lot!

like image 411
trying_hal9000 Avatar asked Nov 05 '11 22:11

trying_hal9000


1 Answers

Some people have more than two names, such as "John Clark Smith". You can choose to treat them as:

(1) first_name: "John", last_name: "Smith"

  def first_name
    if name.split.count > 1
      name.split.first
    else
      name
    end
  end

  def last_name
    if name.split.count > 1
      name.split.last
    end
  end

(2) first_name: "John Clark", last_name: "Smith"

  def first_name
    if name.split.count > 1
      name.split[0..-2].join(' ')
    else
      name
    end
  end

  def last_name
    if name.split.count > 1
      name.split.last
    end
  end

(3) first_name: "John", last_name: "Clark Smith"

  def first_name
    name.split.first
  end

  def last_name
    if name.split.count > 1
      name.split[1..-1].join(' ')
    end
  end

The above examples assume that if the name contains less than 2 words then it is a first name.

like image 166
Nicolas Kokkalis Avatar answered Jan 04 '23 11:01

Nicolas Kokkalis