简体   繁体   中英

Replace empty values in array of hashes in ruby

I have an array of hashes.. some field values are blank ie value => ""

When I try to save them in db I get this error -- Column count doesn't match value count at row 1 (Mysql::Error) --which is basically when columns and value dont match...

I cannot try to match the column and values..... for some the data might be empty and for others values might be there..

So the best way seems to be to replace empty value ie value => "" into putting a "-" there ie value => "-"

I want to do change this {"value"=>"", "field"=>"x"} to
{"value"=>"-", "field"=>"x"}

In Ruby

I have tried the below options of alex and dan - but I am still getting errors.. might be this can help... the output I have is like

data = {"title"=>"Book1set", "id"=>"4899364", "columns"=>[{"name"=>"", "value"=>"3.85", "field"=>"price", "sort_order"=>""}, {"name"=>"", "value"=>"1.14", "field"=>"tax", "sort_order"=>""}]} {"title"=>"Book2set", "id"=>"4899364", "columns"=>[{"name"=>"", "value"=>"3.85", "field"=>"price", "sort_order"=>""}, {"name"=>"", "value"=>"1.14", "field"=>"tax", "sort_order"=>""}]} ...... (1000 odd title book set series like this..)

and I extract the field and value and save in db...

and in some of it is like this... "value"=>""

which is what I am trying to replace by "value"=>"-"

puts [ {"value"=>"", "field"=>"x"} ].map { |h|
  h.each_key { |k| h[k] = "-" if h[k].length == 0 }
}.inspect

Example output:

$ ruby ./t.rb  
[{"value"=>"-", "field"=>"x"}]

Here is a similar but shorter way to achieve the same result

h = {"value"=>"", "field"=>"x"}
Hash[h.to_a.map {|k, v| [k, v.empty? ? "-" : v] }]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM