2016年4月22日 星期五

each_with_object 好用的地方

each_with_object 好用的地方

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 }


沒有留言:

張貼留言