Ex:(多維展開)
{原本}
def org_users(users)
temp = {}
users.each do |user|
temp[user.group] ||= {}
temp[user.group][user.id] = user
end
temp
end
{改良}
users.each_with_object(Hash.new{ |h,k| h[k] = {} }) { |obj, hash| hash[obj.group][obj.id] = obj }
Ex:(類型計算)
x = ["tiger", "tiger", "cat", "tiger", "dog", "cat"]
x.each_with_object(Hash.new(0)) { |obj, counts| counts[obj] += 1 }