我有这个哈希
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}
有人可以帮忙怎么做?
答案 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}
您可以通过先将所有值转换为数组来稍微干掉代码,但对于nil
和Date
键,您将获得空数组而不是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