我有一个数组:
arr = [["group1", "user1", "user2", "user3", "AD-user1", "AD-user2"],
["group2", "user4"]]
我想做那样的事情:
arr.each do |item|
if (item.include? "AD-user") then
arr_h = { "Group" => arr[1],
"User" => arr[number_of_element_with_AD-user_name] }
else
#something else
end
end
我不知道如何定义if语句中找到的值的索引。在这种情况下,我有两个以&#34开头的用户名; AD-user"字符串,但它可以是很多。组名称始终是子阵列中的第一个值。
答案 0 :(得分:1)
试试这个:
new_ary = []
arr.each do |a|
b = a.select{|e| e.include? "AD-user"}
if b.empty?
#something else
new_ary << {"Group" => a[0], "Users" => "AD-user not available"}
else
new_ary << {"Group" => a[0], "Users" => b}
end
end
> new_ary
#=> [{"Group"=>"group1", "Users"=>["AD-user1", "AD-user2"]}, {"Group"=>"group2", "Users"=>"AD-user not available"}]
new_ary = []
arr.each do |a|
b = a.select{|e| e.include? "AD-user"}
new_ary << {"Group" => a[0], "Users" => b}
end
> new_ary
#=> [{"Group"=>"group1", "Users"=>["AD-user1", "AD-user2"]}, {"Group"=>"group2", "Users"=>[]}]