Topic: Another silly bit of ruby code that needs it's teeth brushed!

  def get_full_name
 
    out = "";
   
    [first_name, last_name, middle_initial].map { |x|
      if x
        if out.length > 0
          out += ", #{x}"
        else
          out += x
        end   
      end
    }
 
    out
 
  end

This should be able to be done in 1 line.  Orignially I tried:

[first_name, last_name, middle_initial].join(',')

but that returns a string with 2 commas -- even if not all 3 things are defined.  In fact, if none of the fields are set, I just want an empty string returned.

smile

Re: Another silly bit of ruby code that needs it's teeth brushed!

Try:

[first_name, last_name, middle_initial].compact.join(', ')

Compact will remove all nil values. If you want blank (empty) values to be removed too you can do this:

[first_name, last_name, middle_initial].reject(&:blank?).join(', ')

Railscasts - Free Ruby on Rails Screencasts

Re: Another silly bit of ruby code that needs it's teeth brushed!

Sorry I'm not the most knowledgeable in this, but can't you just use a simple addition?

def get_full_name
out = "#{first_name}" + "#{last name}" + "#{middle_initial}"
end

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: Another silly bit of ruby code that needs it's teeth brushed!

Simply concatenating the strings won't work because he needs commas separating the values only if the values are set.

Railscasts - Free Ruby on Rails Screencasts

Re: Another silly bit of ruby code that needs it's teeth brushed!

Thank you ryanb.  You're really helpful and nice, and I'm happy that I can ask silly questions like this and get answers.  One thing I'm trying to avoid doing is writing code that "might work just fine", but isn't really using ruby well.

Thanks for all your help so far!

Re: Another silly bit of ruby code that needs it's teeth brushed!

Slurpy wrote:

One thing I'm trying to avoid doing is writing code that "might work just fine", but isn't really using ruby well.

Exactly. I wish everyone had the same goal. I'm a big fan of clean code and using Ruby to its full potential through that. smile

Railscasts - Free Ruby on Rails Screencasts