我的表中有一列有以下字符串值:
arr = ["First Name", "Last Name", "location", "Description"]
我需要按顺序将每个值映射到字母:
["A", "B", "C", "D"]
这些字母不是表格的一部分,也没有定义,但我倾向于使用上面的arr创建一个小哈希,除非有更好的建议?
我需要能够将每个字母映射到arr中的对应值,并且当arr在视图中更新时,每个字母应该在arr中对应。例如,如果"名字"从arr中移除,然后第一个应该是" B"或者如果"位置"如果删除,则新数组应为" A"," B"," D"。意思是,在创建或更新时,字母应始终映射到arr中的相应值。我希望我有意义吗?
非常感谢。
答案 0 :(得分:1)
例如你有
arr = ["First Name", "Last Name", "location", "Description"]
arr_hash= Hash.new
and yout have a instance for
@client =Client.first
hash[0] = []
hash[0] << arr
hash[1] = []
hash[1] << @client
以及更多....
答案 1 :(得分:0)
您可以先使用对,然后删除更新数组中不存在的键。
arr = ["First Name", "Last Name", "location", "Description"]
arr2 = ["A", "B", "C", "D"]
result = Hash[arr.zip(arr2)]
# => {"First Name"=>"A", "Last Name"=>"B", "location"=>"C", "Description"=>"D"}
# update original arr like:
arr = ["Last Name", "location", "Description"]
result.delete_if { |k, _| !arr.include?(k) }
# => {"Last Name"=>"B", "location"=>"C", "Description"=>"D"}