我正在尝试在数组中发送关键值的一些数据,但是难以接受。
这是我的数组中的内容:
data = [ "name=abc", "title=analyst", "group=IT", "id=123"]
我想要翻译的地图:
mapping = { "name" => "EmployeeName", "title" => "JobTitle", "group" => "BusinessGroup", "id" => "EmployeeID"}
我追求的预期结果:
data = [ "EmployeeName=abc", "JobTitle=analyst", "BusinessGroup=IT", "EmployeeID=123"]
答案 0 :(得分:2)
data.map {|s| s.sub /\w+/, mapping }
# => ["EmployeeName=abc", "JobTitle=analyst", "BusinessGroup=IT", "EmployeeID=123"]
答案 1 :(得分:1)
data.map { |str| str.split(/\s*=\s*/).tap { |k,_| k.replace(mapping[k]) }.join('=') }
#=> ["EmployeeName=abc", "JobTitle=analyst", "BusinessGroup=IT", "EmployeeID=123"]
如果/\s*=\s*/
之前或之后有任何空格,我会在"="
而不是=
上拆分。
答案 2 :(得分:0)
根据您的data
数组和mapping
哈希,您可以使用Array#map执行以下操作:
data.map do |i|
key, value = i.split('=')
"#{mapping[key]}=#{value}"
end
# => ["EmployeeName=abc", "JobTitle=analyst", "BusinessGroup=IT", # "EmployeeID=123"]
答案 3 :(得分:0)
> data.map{|a| a.split("=")}.map{|e| mapping.has_key?(e[0]) ? "#{e[0] = mapping[e[0]]}=#{e[1]}" : "#{e[0]}\=#{e[1]}"}
=> ["EmployeeName=abc", "JobTitle=analyst", "BusinessGroup=IT", "EmployeeID=123"]