Nikolay Lipovtsev
Nikolay Lipovtsev

Reputation: 679

Ruby on Rails 4 - Simplify concat

How I can simplify this method?

def concat_arg(a, b)
  if b.any?
    a.concat(b)
  else
    a
  end
end 

Upvotes: 0

Views: 62

Answers (2)

AJFaraday
AJFaraday

Reputation: 2450

If your intention is to add a string to the end of an array, you don't need concat, which is mostly used to add the content of one array to another. Try this:

["apple","potato"] << "onion"
# => 
["apple","potato", "onion"]

Or, to handle the conditional:

foods << food if food and !food.blank?

You may find you don't need this method, it depends what you're trying to achieve.

Note: this behaviour may be different in ruby 2.x, have a play with it first to check how it handles nils

Upvotes: 0

jklina
jklina

Reputation: 3417

If you're worried about B being nil you could do something like

def concat_arg(A, B='')
  A.concat(B)
end 

Upvotes: 1

Related Questions