byCoder
byCoder

Reputation: 9184

Ruby csv import get code smaller but equal

I'm new to rails and ruby... How can i refactor such code, which import's from csv file data? Now i have such code

  if row[qnt].to_s != ""
    eqnt = /(\d+)/.match(row[qnt])[0].to_s
  else
    eqnt = 0
  end

I try something like

if row[qnt].present?
        eqnt = /(\d+)/.match(row[qnt])[0].to_s
      else
        eqnt = 0
      end

But is it equal, and also what else could i do to get code smaller?

Upvotes: 0

Views: 75

Answers (3)

Casper
Casper

Reputation: 34308

eqnt = (/(\d+)/.match(row[qnt]) || [0])[0]

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

I'm not convinced the code gains readability by trying to compress it much further.

eqnt = row[qnt].present? ? /(\d+)/.match(row[qnt])[0].to_s : 0

Or

eqnt = 0
eqnt = /(\d+)/.match(row[qnt])[0].to_s if row[qnt].present?

Or

theRow = row[qnt]
eqnt = theRow.present? ? /(\d+)/.match(theRow).first.to_s : 0

Or better yet, extract this into a method, keep the mainline code clean, and isolate the logic.

I'm not psyched about eqnt ending up with different types, though, unless that's by design.

Upvotes: 0

Leo Correa
Leo Correa

Reputation: 19789

How about this?

row[qnt].present? ? eqnt = /(\d+)/.match(row[qnt])[0].to_s : eqnt = 0

Upvotes: 1

Related Questions