Blair Anderson
Blair Anderson

Reputation: 20171

rails hash extract first value from list

I am trying to normalize some data in an ETL process because the data we get is not consistent.

Annoying but i am here to learn.

currently we do something like:

received = datum[:quantity_received] || datum[:received_cases] || datum[:received_quantity]

Curious if there is a more ruby/rails way of doing this?

considering:

received = datum.values_at(:quantity_received,:received_cases,:received_quantity).compact.first

Upvotes: 0

Views: 94

Answers (1)

Ursus
Ursus

Reputation: 30056

I don't think there is a much better solution. I'd try to define some helper methods (I'm not a long lines' supporter)

def value_you_need(datum)
  datum.values_at(*keys_of_interest).find(&:itself)
end

def keys_of_interest
  %i(quantity_received received_cases received_quantity)
end

received = value_you_need(datum)

object#itself method is present from ruby 2.2.0. Otherwise, go for compact.first.

Note a detail: if false is one of the values you care about the solution with compact.first is the only one correct of our three. But I took for granted you don't or the first option would be wrong.

Upvotes: 1

Related Questions