Demian Sims
Demian Sims

Reputation: 921

How do I find and replace 'nil' values of Ruby hash with "None" or 0?

I'm trying to drill down to each value in an iteration of an array nested hash and replace all nil values with something like 'None' or 0. Please see my code that is clearly not working. I need to fix this before I pass it to my Views in Rails for iteration and rendering:

My controller:

def show
  results = Record.get_record(params[:trans_uuid])
  if !results.empty?
    record = results.map { |res| res.attributes.symbolize_keys }
    @record = Record.replace_nil(record) # this calls method in Model
  else
    flash[:error] = 'No record found'
  end
end

My model:

def self.replace_nil(record)
  record.each do |r|
    r.values == nil ? "None" : r.values
  end
end

record looks like this when passed to Model method self.replace_nil(record:

[{:id=>1, :time_inserted=>Wed, 03 Apr 2019 15:41:06 UTC +00:00, :time_modified=>nil, :request_state=>"NY", :trans_uuid=>"fe27813c-561c-11e9-9284-0282b642e944", :sent_to_state=>-1, :completed=>-1, :record_found=>-1, :retry_flag=>-1, :chargeable=>-1, :note=>"", :bridge_resultcode=>"xxxx", :bridge_charges=>-1}]

Upvotes: 6

Views: 4094

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

each won't "persist" the value you're yielding within the block. Try map instead.

def self.replace_nil(record) 
  record.map do |r| 
    r.values.nil? ? "None" : r.values
  end 
end

In fact, there's a method for that; transform_values:

record.transform_values do |value|
   value.nil? ? 'None' : value
end

I realized that using Rails you can use just presence and the or operator:

record.transform_values do |value|
  value.presence || 'None'
end

Upvotes: 12

Related Questions