0

I have a function generate_username that generates a username (obviously).

The values fname and lname are mandatory, so no issues there. However, mname is NOT a mandatory field so, it may be blank, which breaks this code.

Any suggestions on how to ask ruby to only print the mname value if it exists or is set and ignore it if the user left it blank?

def generate_username
  self.username = fname.to_s.split("")[0] + mname.to_s.split("")[0] + lname.to_s
end
3
  • 1
    why are you splitting then taking the first element, why not just do a strip or gsub if you are trying to do something Commented Apr 17, 2011 at 20:50
  • I'm new to ruby so I'm not sure of the best techniques to grab the first letter of a string, but I'll look these up thanks :) Commented Apr 17, 2011 at 20:55
  • You are a member for two months, asked 10 questions, and so far accepted none of them. I should have noticed that before I answered it. Then, I wouldn't have answered. Commented Apr 19, 2011 at 0:55

3 Answers 3

1

You could try this (parentheses are important):

def generate_username
  self.username = fname.to_s.split("")[0] << (mname.to_s.split("")[0] || "") << lname.to_s
end
Sign up to request clarification or add additional context in comments.

5 Comments

Hm, this seems sound to me, but I'm getting a can't find '+' function. Thanks, though (for putting up with my newb question)
Did you put the parentheses? (in case the error was: NoMethodError: undefined method `+' for false:FalseClass)
Helped a bit but still getting can't convert nil into String
Indeed it returns nil, didn't see this coming. Bear with me a moment :) I am coming back.
Cool! If it works and helped don't forget to check it as an accepted answer :)
1

Throwing a simple ternary operator in to check if the value is blank? should do the trick.

def generate_username
  self.username = fname.to_s.split("")[0] + (mname.blank? ? "" : mname.to_s.split("")[0]) + lname.to_s
end

Comments

1

In ruby 1.9

def generate_username
  "#{fname[0]}#{mname.to_s[0]}#{lname}"
end

or

def generate_username
  fname[0]+mname.to_s[0].to_s+lname
end

In ruby 1.8, replace all the [0] with [0, 1] (This point added after being pointed out by Peter).

  • mname.to_s ensures you get a string; when mname is nil it will be an empty string "".
  • String#[0] picks up the first character of that string; when the string is empty, it will return nil.
  • #{ } within " " expands the ruby code, and turns it into a string; particularly turns nil into an empty string "".

3 Comments

+1! But in my 1.8.7 ruby, fname[0] gives me a Fixnum instead of the first character (while 1.9.2 gives me the first character ;D)
@PeterWong I forgot about that. In ruby1.8.7, probably [0,1] will work.
Love the simplicity of fname[0] over fname.split("")[0] :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.