How can I replace null values with a string when using tohash.select?How can I “pretty” format my JSON output in Ruby on Rails?How to generate a random string in RubyHow can I set default values in ActiveRecord?How to convert a string to lower or upper case in RubyHow can I rename a database column in a Ruby on Rails migration?how to convert a hash into an array with particular order? (ruby)Convert hash keys to lowercase — Ruby BeginnerHow to check whether a string contains a substring in Ruby?How to parse a csv string and convert into a HashGenerate random data before active_admin_import

What is this end portal thingy?

Is there any exception that proves or suggests that the law of non-contradiction does not always apply?

Are the coefficients of certain product of Rogers-Ramanujan Continued Fraction non-negative?

Is it ok if I haven't decided my research topic when I first meet with a potential phd advisor?

LM324 - Issue with output in negative feedback

What can Thomas Cook customers who have not yet departed do now it has stopped operating?

How to stop the death waves in my city?

How much horsepower to weight is required for a 1:1 thrust ratio?

Speed and Velocity in Russian

Where to find the Arxiv endorsement code?

Does the app TikTok violate trademark?

What in my code changed between MacTeX 2017 and MacTex 2019?

As a team leader is it appropriate to bring in fundraiser candy?

A word that refers to saying something in an attempt to anger or embarrass someone into doing something that they don’t want to do?

Science fiction episode about the creation of a living pegasus, even though flightless

Why, even after his imprisonment, people keep calling Hannibal Lecter "Doctor"?

Would an object shot from earth fall into the sun?

What does `idem` mean in the VIM docs?

Question about a degree 5 polynomial with no rational roots

When did Unix stop storing passwords in clear text?

Do interval ratios take overtones into account or solely the fundamental frequency?

What does it mean by "my days-of-the-week underwear only go to Thursday" in this context?

How deep is the liquid in a half-full hemisphere?

Can I target any number of creatures, even if the ability would have no effect?



How can I replace null values with a string when using tohash.select?


How can I “pretty” format my JSON output in Ruby on Rails?How to generate a random string in RubyHow can I set default values in ActiveRecord?How to convert a string to lower or upper case in RubyHow can I rename a database column in a Ruby on Rails migration?how to convert a hash into an array with particular order? (ruby)Convert hash keys to lowercase — Ruby BeginnerHow to check whether a string contains a substring in Ruby?How to parse a csv string and convert into a HashGenerate random data before active_admin_import






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Please forgive me if I'm unclear, but this is pretty difficult to describe in words. I'm using Ruby for a Rails application to take in values from a CSV file row by row, using Ruby's tohash.select function to generate a hash table of all of the key-value pairs for each row, and then using the create function to generate a table of the rows.



The code works for creating a database table from a CSV, but many records within the CSV have null values for some of the fields/columns. I'd like to have those null values converted to a string like "null" when inserting each row in the CSV to the hash table.



I've tried using a regex to replace the null values with a string, but it hasn't worked. I very well may just be doing it wrong.



require 'csv'

fields = %wlVoterUniqueID sAffNumber szStateVoterID sVoterTitle szNameLast szNameFirst szNameMiddle sNameSuffix sGender szSitusAddress szSitusCity sSitusState sSitusZip sHouseNum sUnitAbbr sUnitNum szStreetName sStreetSuffix sPreDir sPostDir szMailAddress1 szMailAddress2 szMailAddress3 szMailAddress4 szMailZip szPhone szEmailAddress dtBirthDate sBirthPlace dtRegDate dtOrigRegDate dtLastUpdate_dt sStatusCode szStatusReasonDesc sUserCode1 sUserCode2 iDuplicateIDFlag szLanguageName szPartyName szAVStatusAbbr szAVStatusDesc szPrecinctName sPrecinctID sPrecinctPortion sDistrictID_0 iSubDistrict_0 szDistrictName_0 sDistrictID_1 iSubDistrict_1 szDistrictName_1 sDistrictID_2 iSubDistrict_2 szDistrictName_2 sDistrictID_3 iSubDistrict_3 szDistrictName_3 sDistrictID_4 iSubDistrict_4 szDistrictName_4 sDistrictID_5 iSubDistrict_5 szDistrictName_5

if Rails.env.production?
CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
voter_row = row.to_hash.select fields.include?(k)
Voter.create!(voter_row.to_hash.symbolize_keys)
end
elsif Rails.env.development?
CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
voter_row = row.to_hash.select fields.include?(k)
Voter.create!(voter_row.to_hash.symbolize_keys)
end
else
CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
voter_row = row.to_hash.select fields.include?(k)
Voter.create!(voter_row.to_hash.symbolize_keys)
end
end


Wherever I am using row.tohash.select, I'd like to replace null values with an empty string, that way every key in the hash table has a corresponding string ("null" if there is no value).










share|improve this question






























    0















    Please forgive me if I'm unclear, but this is pretty difficult to describe in words. I'm using Ruby for a Rails application to take in values from a CSV file row by row, using Ruby's tohash.select function to generate a hash table of all of the key-value pairs for each row, and then using the create function to generate a table of the rows.



    The code works for creating a database table from a CSV, but many records within the CSV have null values for some of the fields/columns. I'd like to have those null values converted to a string like "null" when inserting each row in the CSV to the hash table.



    I've tried using a regex to replace the null values with a string, but it hasn't worked. I very well may just be doing it wrong.



    require 'csv'

    fields = %wlVoterUniqueID sAffNumber szStateVoterID sVoterTitle szNameLast szNameFirst szNameMiddle sNameSuffix sGender szSitusAddress szSitusCity sSitusState sSitusZip sHouseNum sUnitAbbr sUnitNum szStreetName sStreetSuffix sPreDir sPostDir szMailAddress1 szMailAddress2 szMailAddress3 szMailAddress4 szMailZip szPhone szEmailAddress dtBirthDate sBirthPlace dtRegDate dtOrigRegDate dtLastUpdate_dt sStatusCode szStatusReasonDesc sUserCode1 sUserCode2 iDuplicateIDFlag szLanguageName szPartyName szAVStatusAbbr szAVStatusDesc szPrecinctName sPrecinctID sPrecinctPortion sDistrictID_0 iSubDistrict_0 szDistrictName_0 sDistrictID_1 iSubDistrict_1 szDistrictName_1 sDistrictID_2 iSubDistrict_2 szDistrictName_2 sDistrictID_3 iSubDistrict_3 szDistrictName_3 sDistrictID_4 iSubDistrict_4 szDistrictName_4 sDistrictID_5 iSubDistrict_5 szDistrictName_5

    if Rails.env.production?
    CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
    voter_row = row.to_hash.select fields.include?(k)
    Voter.create!(voter_row.to_hash.symbolize_keys)
    end
    elsif Rails.env.development?
    CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
    voter_row = row.to_hash.select fields.include?(k)
    Voter.create!(voter_row.to_hash.symbolize_keys)
    end
    else
    CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
    voter_row = row.to_hash.select fields.include?(k)
    Voter.create!(voter_row.to_hash.symbolize_keys)
    end
    end


    Wherever I am using row.tohash.select, I'd like to replace null values with an empty string, that way every key in the hash table has a corresponding string ("null" if there is no value).










    share|improve this question


























      0












      0








      0








      Please forgive me if I'm unclear, but this is pretty difficult to describe in words. I'm using Ruby for a Rails application to take in values from a CSV file row by row, using Ruby's tohash.select function to generate a hash table of all of the key-value pairs for each row, and then using the create function to generate a table of the rows.



      The code works for creating a database table from a CSV, but many records within the CSV have null values for some of the fields/columns. I'd like to have those null values converted to a string like "null" when inserting each row in the CSV to the hash table.



      I've tried using a regex to replace the null values with a string, but it hasn't worked. I very well may just be doing it wrong.



      require 'csv'

      fields = %wlVoterUniqueID sAffNumber szStateVoterID sVoterTitle szNameLast szNameFirst szNameMiddle sNameSuffix sGender szSitusAddress szSitusCity sSitusState sSitusZip sHouseNum sUnitAbbr sUnitNum szStreetName sStreetSuffix sPreDir sPostDir szMailAddress1 szMailAddress2 szMailAddress3 szMailAddress4 szMailZip szPhone szEmailAddress dtBirthDate sBirthPlace dtRegDate dtOrigRegDate dtLastUpdate_dt sStatusCode szStatusReasonDesc sUserCode1 sUserCode2 iDuplicateIDFlag szLanguageName szPartyName szAVStatusAbbr szAVStatusDesc szPrecinctName sPrecinctID sPrecinctPortion sDistrictID_0 iSubDistrict_0 szDistrictName_0 sDistrictID_1 iSubDistrict_1 szDistrictName_1 sDistrictID_2 iSubDistrict_2 szDistrictName_2 sDistrictID_3 iSubDistrict_3 szDistrictName_3 sDistrictID_4 iSubDistrict_4 szDistrictName_4 sDistrictID_5 iSubDistrict_5 szDistrictName_5

      if Rails.env.production?
      CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
      voter_row = row.to_hash.select fields.include?(k)
      Voter.create!(voter_row.to_hash.symbolize_keys)
      end
      elsif Rails.env.development?
      CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
      voter_row = row.to_hash.select fields.include?(k)
      Voter.create!(voter_row.to_hash.symbolize_keys)
      end
      else
      CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
      voter_row = row.to_hash.select fields.include?(k)
      Voter.create!(voter_row.to_hash.symbolize_keys)
      end
      end


      Wherever I am using row.tohash.select, I'd like to replace null values with an empty string, that way every key in the hash table has a corresponding string ("null" if there is no value).










      share|improve this question














      Please forgive me if I'm unclear, but this is pretty difficult to describe in words. I'm using Ruby for a Rails application to take in values from a CSV file row by row, using Ruby's tohash.select function to generate a hash table of all of the key-value pairs for each row, and then using the create function to generate a table of the rows.



      The code works for creating a database table from a CSV, but many records within the CSV have null values for some of the fields/columns. I'd like to have those null values converted to a string like "null" when inserting each row in the CSV to the hash table.



      I've tried using a regex to replace the null values with a string, but it hasn't worked. I very well may just be doing it wrong.



      require 'csv'

      fields = %wlVoterUniqueID sAffNumber szStateVoterID sVoterTitle szNameLast szNameFirst szNameMiddle sNameSuffix sGender szSitusAddress szSitusCity sSitusState sSitusZip sHouseNum sUnitAbbr sUnitNum szStreetName sStreetSuffix sPreDir sPostDir szMailAddress1 szMailAddress2 szMailAddress3 szMailAddress4 szMailZip szPhone szEmailAddress dtBirthDate sBirthPlace dtRegDate dtOrigRegDate dtLastUpdate_dt sStatusCode szStatusReasonDesc sUserCode1 sUserCode2 iDuplicateIDFlag szLanguageName szPartyName szAVStatusAbbr szAVStatusDesc szPrecinctName sPrecinctID sPrecinctPortion sDistrictID_0 iSubDistrict_0 szDistrictName_0 sDistrictID_1 iSubDistrict_1 szDistrictName_1 sDistrictID_2 iSubDistrict_2 szDistrictName_2 sDistrictID_3 iSubDistrict_3 szDistrictName_3 sDistrictID_4 iSubDistrict_4 szDistrictName_4 sDistrictID_5 iSubDistrict_5 szDistrictName_5

      if Rails.env.production?
      CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
      voter_row = row.to_hash.select fields.include?(k)
      Voter.create!(voter_row.to_hash.symbolize_keys)
      end
      elsif Rails.env.development?
      CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
      voter_row = row.to_hash.select fields.include?(k)
      Voter.create!(voter_row.to_hash.symbolize_keys)
      end
      else
      CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
      voter_row = row.to_hash.select fields.include?(k)
      Voter.create!(voter_row.to_hash.symbolize_keys)
      end
      end


      Wherever I am using row.tohash.select, I'd like to replace null values with an empty string, that way every key in the hash table has a corresponding string ("null" if there is no value).







      ruby-on-rails ruby






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 28 at 19:30









      Matt McMatt Mc

      153 bronze badges




      153 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          1
















          There is Hash#transform_values method that does the job in a clean and idiomatic way. I'd also suggest using Hash#slice instead of #select:



          ...
          CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
          attrs = row.to_hash.slice(*fields).transform_values v
          Voter.create!(attrs)
          end
          ...


          But to be honest, in practice, I'd propose another solution - using default values for database columns if possible instead of "normalizing" the data on the app level.






          share|improve this answer

























          • Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

            – Matt Mc
            Mar 29 at 4:24


















          0
















          You have to iterate over the values and set them where appropriate.



          if Rails.env.production?
          CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'utf-8', headers: true) do |row|
          voter_row = row.to_hash.select fields.include?(k)
          voter_row.each do |key, value|
          if value.nil?
          voter_row[key] = "null"
          end
          end
          Voter.create!(voter_row.to_hash.symbolize_keys)
          end
          else
          CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
          voter_row = row.to_hash.select fields.include?(k)
          voter_row.each do |key, value|
          if value.nil?
          voter_row[key] = "null"
          end
          end
          Voter.create!(voter_row.to_hash.symbolize_keys)
          end


          I also think your elseif/else is redundant, unless I'm missing something.






          share|improve this answer
































            0
















            This sounds like a job for Hash#transform_values:



            h = voter_row.transform_values v


            Couple other things:




            1. You might want to use Hash#slice instead of #select:



              voter_row = row.to_h.slice(*fields)


            2. create is happy with string keys so you don't need to call #symbolize_keys.


            You can simplify your CSV.foreach blocks to just this:



            Voter.create!(row.to_h.slice(*fields))


            You could go further and write:



            opts = headers: true 
            if Rails.env.production?
            csv_file = 'db/prod.csv'
            opts[:encoding] 'iso-8859-1:utf-8'
            elsif Rails.env.development?
            csv_file = 'db/Cntywd_020819.csv'
            else
            csv_file = 'db/Cntywd_020819.csv'
            end
            CSV.foreach(Rails.root.join(csv_file), opts) do |row|
            Voter.create!(row.to_h.slice(*fields))
            end





            share|improve this answer

























            • typo in ...transform_values v - missing space after nil?

              – Konstantin Strukov
              Mar 28 at 20:08











            • @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

              – mu is too short
              Mar 28 at 20:15












            • Cool, I never saw this form. TIL :)

              – Konstantin Strukov
              Mar 28 at 20:17













            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );














            draft saved

            draft discarded
















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405523%2fhow-can-i-replace-null-values-with-a-string-when-using-tohash-select%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1
















            There is Hash#transform_values method that does the job in a clean and idiomatic way. I'd also suggest using Hash#slice instead of #select:



            ...
            CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
            attrs = row.to_hash.slice(*fields).transform_values v
            Voter.create!(attrs)
            end
            ...


            But to be honest, in practice, I'd propose another solution - using default values for database columns if possible instead of "normalizing" the data on the app level.






            share|improve this answer

























            • Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

              – Matt Mc
              Mar 29 at 4:24















            1
















            There is Hash#transform_values method that does the job in a clean and idiomatic way. I'd also suggest using Hash#slice instead of #select:



            ...
            CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
            attrs = row.to_hash.slice(*fields).transform_values v
            Voter.create!(attrs)
            end
            ...


            But to be honest, in practice, I'd propose another solution - using default values for database columns if possible instead of "normalizing" the data on the app level.






            share|improve this answer

























            • Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

              – Matt Mc
              Mar 29 at 4:24













            1














            1










            1









            There is Hash#transform_values method that does the job in a clean and idiomatic way. I'd also suggest using Hash#slice instead of #select:



            ...
            CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
            attrs = row.to_hash.slice(*fields).transform_values v
            Voter.create!(attrs)
            end
            ...


            But to be honest, in practice, I'd propose another solution - using default values for database columns if possible instead of "normalizing" the data on the app level.






            share|improve this answer













            There is Hash#transform_values method that does the job in a clean and idiomatic way. I'd also suggest using Hash#slice instead of #select:



            ...
            CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'iso-8859-1:utf-8', headers: true) do |row|
            attrs = row.to_hash.slice(*fields).transform_values v
            Voter.create!(attrs)
            end
            ...


            But to be honest, in practice, I'd propose another solution - using default values for database columns if possible instead of "normalizing" the data on the app level.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 28 at 20:07









            Konstantin StrukovKonstantin Strukov

            6913 silver badges8 bronze badges




            6913 silver badges8 bronze badges















            • Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

              – Matt Mc
              Mar 29 at 4:24

















            • Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

              – Matt Mc
              Mar 29 at 4:24
















            Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

            – Matt Mc
            Mar 29 at 4:24





            Brilliant! I did both. The dataset seeds perfectly now and sets all null values to "null".

            – Matt Mc
            Mar 29 at 4:24













            0
















            You have to iterate over the values and set them where appropriate.



            if Rails.env.production?
            CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'utf-8', headers: true) do |row|
            voter_row = row.to_hash.select fields.include?(k)
            voter_row.each do |key, value|
            if value.nil?
            voter_row[key] = "null"
            end
            end
            Voter.create!(voter_row.to_hash.symbolize_keys)
            end
            else
            CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
            voter_row = row.to_hash.select fields.include?(k)
            voter_row.each do |key, value|
            if value.nil?
            voter_row[key] = "null"
            end
            end
            Voter.create!(voter_row.to_hash.symbolize_keys)
            end


            I also think your elseif/else is redundant, unless I'm missing something.






            share|improve this answer





























              0
















              You have to iterate over the values and set them where appropriate.



              if Rails.env.production?
              CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'utf-8', headers: true) do |row|
              voter_row = row.to_hash.select fields.include?(k)
              voter_row.each do |key, value|
              if value.nil?
              voter_row[key] = "null"
              end
              end
              Voter.create!(voter_row.to_hash.symbolize_keys)
              end
              else
              CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
              voter_row = row.to_hash.select fields.include?(k)
              voter_row.each do |key, value|
              if value.nil?
              voter_row[key] = "null"
              end
              end
              Voter.create!(voter_row.to_hash.symbolize_keys)
              end


              I also think your elseif/else is redundant, unless I'm missing something.






              share|improve this answer



























                0














                0










                0









                You have to iterate over the values and set them where appropriate.



                if Rails.env.production?
                CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'utf-8', headers: true) do |row|
                voter_row = row.to_hash.select fields.include?(k)
                voter_row.each do |key, value|
                if value.nil?
                voter_row[key] = "null"
                end
                end
                Voter.create!(voter_row.to_hash.symbolize_keys)
                end
                else
                CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
                voter_row = row.to_hash.select fields.include?(k)
                voter_row.each do |key, value|
                if value.nil?
                voter_row[key] = "null"
                end
                end
                Voter.create!(voter_row.to_hash.symbolize_keys)
                end


                I also think your elseif/else is redundant, unless I'm missing something.






                share|improve this answer













                You have to iterate over the values and set them where appropriate.



                if Rails.env.production?
                CSV.foreach(Dir.pwd + "/db/prod.csv", encoding: 'utf-8', headers: true) do |row|
                voter_row = row.to_hash.select fields.include?(k)
                voter_row.each do |key, value|
                if value.nil?
                voter_row[key] = "null"
                end
                end
                Voter.create!(voter_row.to_hash.symbolize_keys)
                end
                else
                CSV.foreach(Dir.pwd + "/db/Cntywd_020819.csv", headers: true) do |row|
                voter_row = row.to_hash.select fields.include?(k)
                voter_row.each do |key, value|
                if value.nil?
                voter_row[key] = "null"
                end
                end
                Voter.create!(voter_row.to_hash.symbolize_keys)
                end


                I also think your elseif/else is redundant, unless I'm missing something.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 28 at 19:57









                Veridian DynamicsVeridian Dynamics

                1,1811 gold badge3 silver badges13 bronze badges




                1,1811 gold badge3 silver badges13 bronze badges
























                    0
















                    This sounds like a job for Hash#transform_values:



                    h = voter_row.transform_values v


                    Couple other things:




                    1. You might want to use Hash#slice instead of #select:



                      voter_row = row.to_h.slice(*fields)


                    2. create is happy with string keys so you don't need to call #symbolize_keys.


                    You can simplify your CSV.foreach blocks to just this:



                    Voter.create!(row.to_h.slice(*fields))


                    You could go further and write:



                    opts = headers: true 
                    if Rails.env.production?
                    csv_file = 'db/prod.csv'
                    opts[:encoding] 'iso-8859-1:utf-8'
                    elsif Rails.env.development?
                    csv_file = 'db/Cntywd_020819.csv'
                    else
                    csv_file = 'db/Cntywd_020819.csv'
                    end
                    CSV.foreach(Rails.root.join(csv_file), opts) do |row|
                    Voter.create!(row.to_h.slice(*fields))
                    end





                    share|improve this answer

























                    • typo in ...transform_values v - missing space after nil?

                      – Konstantin Strukov
                      Mar 28 at 20:08











                    • @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

                      – mu is too short
                      Mar 28 at 20:15












                    • Cool, I never saw this form. TIL :)

                      – Konstantin Strukov
                      Mar 28 at 20:17















                    0
















                    This sounds like a job for Hash#transform_values:



                    h = voter_row.transform_values v


                    Couple other things:




                    1. You might want to use Hash#slice instead of #select:



                      voter_row = row.to_h.slice(*fields)


                    2. create is happy with string keys so you don't need to call #symbolize_keys.


                    You can simplify your CSV.foreach blocks to just this:



                    Voter.create!(row.to_h.slice(*fields))


                    You could go further and write:



                    opts = headers: true 
                    if Rails.env.production?
                    csv_file = 'db/prod.csv'
                    opts[:encoding] 'iso-8859-1:utf-8'
                    elsif Rails.env.development?
                    csv_file = 'db/Cntywd_020819.csv'
                    else
                    csv_file = 'db/Cntywd_020819.csv'
                    end
                    CSV.foreach(Rails.root.join(csv_file), opts) do |row|
                    Voter.create!(row.to_h.slice(*fields))
                    end





                    share|improve this answer

























                    • typo in ...transform_values v - missing space after nil?

                      – Konstantin Strukov
                      Mar 28 at 20:08











                    • @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

                      – mu is too short
                      Mar 28 at 20:15












                    • Cool, I never saw this form. TIL :)

                      – Konstantin Strukov
                      Mar 28 at 20:17













                    0














                    0










                    0









                    This sounds like a job for Hash#transform_values:



                    h = voter_row.transform_values v


                    Couple other things:




                    1. You might want to use Hash#slice instead of #select:



                      voter_row = row.to_h.slice(*fields)


                    2. create is happy with string keys so you don't need to call #symbolize_keys.


                    You can simplify your CSV.foreach blocks to just this:



                    Voter.create!(row.to_h.slice(*fields))


                    You could go further and write:



                    opts = headers: true 
                    if Rails.env.production?
                    csv_file = 'db/prod.csv'
                    opts[:encoding] 'iso-8859-1:utf-8'
                    elsif Rails.env.development?
                    csv_file = 'db/Cntywd_020819.csv'
                    else
                    csv_file = 'db/Cntywd_020819.csv'
                    end
                    CSV.foreach(Rails.root.join(csv_file), opts) do |row|
                    Voter.create!(row.to_h.slice(*fields))
                    end





                    share|improve this answer













                    This sounds like a job for Hash#transform_values:



                    h = voter_row.transform_values v


                    Couple other things:




                    1. You might want to use Hash#slice instead of #select:



                      voter_row = row.to_h.slice(*fields)


                    2. create is happy with string keys so you don't need to call #symbolize_keys.


                    You can simplify your CSV.foreach blocks to just this:



                    Voter.create!(row.to_h.slice(*fields))


                    You could go further and write:



                    opts = headers: true 
                    if Rails.env.production?
                    csv_file = 'db/prod.csv'
                    opts[:encoding] 'iso-8859-1:utf-8'
                    elsif Rails.env.development?
                    csv_file = 'db/Cntywd_020819.csv'
                    else
                    csv_file = 'db/Cntywd_020819.csv'
                    end
                    CSV.foreach(Rails.root.join(csv_file), opts) do |row|
                    Voter.create!(row.to_h.slice(*fields))
                    end






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 28 at 19:59









                    mu is too shortmu is too short

                    364k59 gold badges722 silver badges697 bronze badges




                    364k59 gold badges722 silver badges697 bronze badges















                    • typo in ...transform_values v - missing space after nil?

                      – Konstantin Strukov
                      Mar 28 at 20:08











                    • @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

                      – mu is too short
                      Mar 28 at 20:15












                    • Cool, I never saw this form. TIL :)

                      – Konstantin Strukov
                      Mar 28 at 20:17

















                    • typo in ...transform_values v - missing space after nil?

                      – Konstantin Strukov
                      Mar 28 at 20:08











                    • @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

                      – mu is too short
                      Mar 28 at 20:15












                    • Cool, I never saw this form. TIL :)

                      – Konstantin Strukov
                      Mar 28 at 20:17
















                    typo in ...transform_values v - missing space after nil?

                    – Konstantin Strukov
                    Mar 28 at 20:08





                    typo in ...transform_values v - missing space after nil?

                    – Konstantin Strukov
                    Mar 28 at 20:08













                    @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

                    – mu is too short
                    Mar 28 at 20:15






                    @KonstantinStrukov No, that's valid. I find nil?? x : y less visually confusing than nil? ? x : y but that's just personal preference.

                    – mu is too short
                    Mar 28 at 20:15














                    Cool, I never saw this form. TIL :)

                    – Konstantin Strukov
                    Mar 28 at 20:17





                    Cool, I never saw this form. TIL :)

                    – Konstantin Strukov
                    Mar 28 at 20:17


















                    draft saved

                    draft discarded















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405523%2fhow-can-i-replace-null-values-with-a-string-when-using-tohash-select%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript