像以下的情況,key 跟 value 的順序是對應的:
key = ["a", "b", "c", "a", "d", "e"]
value = ["mary", "john","sam", "paul", "kelly", "mary"]
當 key 有超過一個"a", 如何建立一個 Hash 把"mary" & "paul" 都裝進"a" ?
我試過用 zip,但做不到我想要的效果!
myHash = [key.zip(value)]
key.zip(value).group_by { |o| o.first }.map { |k, v| [k, v.map { |i| i.last }] }.to_h
key = ["a", "b", "c", "a", "d", "e"]
value = ["mary", "john","sam", "paul", "kelly", "mary"]
Hash[[key, value].transpose]
transpose 方法如果 key value 数量不对的话会报错的~
class User
attr_accessor :gender, :name
def initialize(arr)
@gender, @name = arr
end
def last_name
@name[0]
end
end
records = %w(男 张三 男 李四 女 张洋 男 李五 女 潘潘).each_slice(2).collect {|arr| User.new arr}
def group_hash(records, attr_k, attr_v)
records.collect(&attr_v).group_by.each_with_index {|v,i| records[i].send(attr_k)}
end
group_hash(records, :gender, :name)
group_hash(records, :last_name, :name)
irb(main):598:0> group_hash(records, :gender, :name) => {"男"=>["张三", "李四", "李五"], "女"=>["张洋", "潘潘"]} irb(main):599:0> group_hash(records, :last_name, :name) => {"张"=>["张三", "张洋"], "李"=>["李四", "李五"], "潘"=>["潘潘"]}
#3 楼 @zj0713001 不符合楼主的要求,你的结果是 {"a"=>"paul", "b"=>"john", "c"=>"sam", "d"=>"kelly", "e"=>"mary"}