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

你。 提交于 2019-12-23 18:52:13

问题


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}]

回答1:


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


来源:https://stackoverflow.com/questions/58241397/how-do-i-find-and-replace-nil-values-of-ruby-hash-with-none-or-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!