Victor
Victor

Reputation: 13378

Rails prepend twice to string

Using Rails 4.2. I have the following:

field = ["can't be blank", "is invalid"]

def error_message_for(field)
  if field.present?
    if field.size > 1
      field.last.prepend("and/or ")
    end
    field.join(", ")
  end
end

error_message_for(field)

I expect the output to be can't be blank, and/or is invalid, but it's can't be blank, and/or and/or is invalid instead. You see and/or appears twice.

What is wrong?

Upvotes: 0

Views: 142

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

String#prepend mutates the string. That said, calls to it are not idempotent. Use the cloned version of fields array:

def error_message_for(field)
  field = field.map(&:dup) # HERE
  if field.present?
    if field.size > 1
      field.last.prepend("and/or ")
    end
    field.join(", ")
  end
end

Upvotes: 2

gwcodes
gwcodes

Reputation: 5690

It looks okay to me. Are you sure you aren't running an old cached version (try restarting rails server), or have any odd monkey-patches in place?

That said, I think what you're trying to achieve is doable in an easier way in Rails: have a look at to_sentence.

This can simplify to:

field.to_sentence(last_word_connector: ' and/or ')

Upvotes: 3

Related Questions