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 }


2016年4月14日 星期四

『*』的用法


「*」的用法 

把 array 展開成豆號分隔的 參數


Ex1:
numbers = [1, 2, 3]
numbers_with_zero_and_100 = [0, *numbers, 100] # => [0, 1, 2, 3, 100]

 Ex2:

def get_year_month
  year_month ||= params[:year_month] || Date.today.strftime("%Y-%m")
  year_month.split(/-|\/|_/).map { |i| i.to_i }
end
Date.new(*(get_year_month)) # =>  Fri, 01 Apr 2016