Search code examples
ruby-on-railsrubypass-by-referencepass-by-value

Ruby how to modify parameters


so i have this code that and my aim was to convert any empty string to null

def convert_empty_strings_to_null
  if request.patch? || request.post?
    convert_empty_strings_to_null_rec(request.params)
  end
end

def convert_empty_strings_to_null_rec(param)
  param = nil if param.empty? if param.is_a?(String)
  param.all?{|v| convert_empty_strings_to_null_rec v} if param.is_a?(Array)
  param.all?{|k,v| convert_empty_strings_to_null_rec v} if param.is_a?(Hash)
end

But i'm new to ruby on rails and i found it that it sends params by value and not by reference, so no change in params is made, how do i fix this ?


Solution

  • I assume that by "empty" you mean zero-with strings, meaning that strings consisting only of whitespace should be left intact. (Otherwise blank? and strip would be your friends.)

    def convert_empty_strings_to_nil
      if request.patch? || request.post?
        request.params.each do |key, value| 
          request.params[key] = convert_empty_strings_to_nil_rec(value)
        end
      end
    end
    
    def convert_empty_strings_to_nil_rec(param)
      case param
      when String
        param.empty? ? nil : param
      when Array
        param.map{ |v| convert_empty_strings_to_nil_rec(v) }
      when Hash
        param.map{ |k,v| [k, convert_empty_strings_to_nil_rec(v)] }.to_h
      else
        param
      end
    end