0

For example, to get the full name of a User model with first_name and last_name attributes, one could write:

def full_name
  self.name_first + " " + self.name_last
end

or

def full_name
  "#{self.name_first} #{self.name_last}"
end

I've noticed that I personally prefer the latter. It may be subjective, but which is generally preferred? What are the advantages/ disadvantages?

ztech
  • 560
  • 5
  • 13
  • 2
    http://stackoverflow.com/a/10076632/2697183 – AbM Aug 05 '15 at 16:51
  • possible duplicate of [String concatenation vs. interpolation in Ruby](http://stackoverflow.com/questions/10076579/string-concatenation-vs-interpolation-in-ruby) – eirikir Aug 05 '15 at 16:55

2 Answers2

1

According to the community Ruby coding style guide (https://github.com/bbatsov/ruby-style-guide#string-interpolation):

Prefer string interpolation and string formatting instead of string concatenation

Also, regarding self (https://github.com/bbatsov/ruby-style-guide#no-self-unless-required):

Avoid self where not required. (It is only required when calling a self write accessor.)

So, finally this method could be something like:

def full_name
  "#{name_first} #{name_last}"
end
markets
  • 6,709
  • 1
  • 38
  • 48
0

The first version – concatenating with + – will raise an error if either attribute is nil or is not of type String.

The second version – using expression substitution – calls to_s on everything substituted, so nil becomes "" and therefore wouldn't raise an error. This also applies to other classes such as Array, Hash, etc. that implement to_s.

eirikir
  • 3,802
  • 3
  • 21
  • 39