提取哈希的错误值

时间:2017-08-29 15:32:20

标签: ruby-on-rails

我有这个哈希

obj= {"User"=>["user_error", "Jack", "Jill1"], "Project"=>[ "project_error", "xxx"], "Task"=>[39], "Date"=>"date_error", "Time (Hours)"=>["time_error", "-2"], "Comment"=>"comment_error"}

我必须提取密钥的错误值并将其存储在其中 。最终结果应该是

error = ["user_error", "project_error","date_error","time_error","comment_error"]


obj = {"User"=>["Jack", "Jill1"], "Project"=>[ "xxx"], "Task"=>[39], "Date"=>nil, "Time (Hours)"=>["-2"], "Comment"=>nil}

有人可以帮忙怎么做?

2 个答案:

答案 0 :(得分:1)

不太漂亮,但你可以这样做:

errors = obj.each_with_object([]) do |(k, v), err|
  if v.is_a?(Array) && v.first =~ /_error$/
    err << v.shift
  elsif v =~ /_error$/
    err << v
    obj[k] = nil
  end
end

结果:

errors
#=> ["user_error", "project_error", "date_error", "time_error", "comment_error"]

obj
#=> {"User"=>["Jack", "Jill1"], "Project"=>["xxx"], "Task"=>[39], "Date"=>nil, "Time (Hours)"=>["-2"], "Comment"=>nil}

您可以通过先将所有值转换为数组来稍微干掉代码,但对于nilDate键,您将获得空数组而不是Comment

errors = obj.each_with_object([]) do |(k, v), err|
  obj[k] = v = [v].flatten
  err << v.shift if v.first =~ /_error$/
end

errors
#=> ["user_error", "project_error", "date_error", "time_error", "comment_error"]

obj
#=> {"User"=>["Jack", "Jill1"], "Project"=>["xxx"], "Task"=>[39], "Date"=>[], "Time (Hours)"=>["-2"], "Comment"=>[]}

答案 1 :(得分:0)

您可以执行以下操作:

errors = []
obj.map do |class_name, strings| 
  errors.push(strings.shift) # shift remove the first element of the array
  obj[class_name] = strings
end