替换ruby中哈希数组中的空值

时间:2014-09-11 22:36:47

标签: ruby-on-rails ruby regex hash

我有一个哈希数组..某些字段值为空,即值=> ""

当我尝试将它们保存在db中时,我收到此错误 - 列计数与第1行的值计数不匹配(Mysql :: Error) - 这基本上是当列和值不匹配时...

我无法尝试匹配列和值.....对于某些数据可能是空的,而其他数据可能在那里..

所以最好的方法似乎是替换空值,即值=> ""投入" - "那里ie value => " - "

我想更改此{"值" =>"","字段" =>" x"}到
{"值" =>" - ","字段" =>" x"}

在Ruby中

我已经尝试过alex和dan的以下选项 - 但我仍然会收到错误..可能这会有所帮助...我的输出就像

data = {" title" =>" Book1set"," id" =>" 4899364","列" => [{"名称" =>"","值" =>" 3.85", "字段" =>"价格"," sort_order" =>""},{"名称" =>"","值" =>" 1.14","字段" =>"税&# 34;," sort_order" =>""}]} {" title" =>" Book2set"," id" =>" 4899364","列" => [{"名称" =>"",& #34;值" =>" 3.85","字段" =>"价格"," sort_order" => ;""},{"名称" =>"","价值" =>" 1.14&# 34;,"字段" =>"税"," sort_order" =>""}]} ..... (1000张奇数书套装系列就像这样..)

然后我提取字段和值并保存在db ...

并且其中一些是这样的......"价值" =>""

这就是我想要用"值" =>" - "

取代

2 个答案:

答案 0 :(得分:0)

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

示例输出:

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

答案 1 :(得分:0)

这是一种类似但更短的方法来实现相同的结果

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