lost9123193
lost9123193

Reputation: 11030

Simply if statement to a Tenerary in Ruby

I'm new to Rails and was wondering about the following:

Is there a way to simplify this further?

  animal = Animal.find_by(name:name, type:type)
  if !animal
    animal = Animal.create(name:name, type:type)

I was thinking of using a ternary expression but i'm wondering how I would write that without repeating code or if this is the correct way of doing it.

animal = Animal.find_by(name:name, type:type) ? Animal.find_by(name:name, type:type) :  Animal.create(name:name, type:type);

Upvotes: 2

Views: 155

Answers (3)

user1934428
user1934428

Reputation: 22225

Just one more variation:

animal = Animal.find_by(name:name, type:type) || Animal.create(name:name, type:type)

Upvotes: 0

Mark
Mark

Reputation: 6445

Try find_or_create_by

animal = Animal.find_or_create_by(name: name, type: type)

Upvotes: 7

3limin4t0r
3limin4t0r

Reputation: 21110

In your specific scenario the answer of Mark is the better answer. However I'd like to offer a clean solution of what you currently have.

Ruby allows an inline modifier-if/unless statement. This would look like this:

animal = Animal.find_by(name: name, type: type)
animal = Animal.create(name: name, type: type) unless animal

You could also make use of the ||= operator here (which has my preference). This operator only assigns the right had value to the variable if the variable currently holds a falsy value (nil or false).

animal = Animal.find_by(name: name, type: type)
animal ||= Animal.create(name: name, type: type)

# or if you prefer the longer one-liner
animal = Animal.find_by(name: name, type: type) || Animal.create(name: name, type: type)

Upvotes: 1

Related Questions