2017-08-29 96 views
0

我有這個哈希的誤差值提取哈希

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

我要提取鍵的誤差值,並將其存儲其他地方 .The最終結果應該是

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} 

有人可以幫助如何做到這一點?

+1

你有什麼迄今所做?告訴我們你的代碼。 –

回答

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} 

你可以通過將所有值轉換爲DRY代碼第一陣列,但你會得到空數組來代替nilDateComment鍵:

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"=>[]} 
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