Created
July 5, 2013 05:26
-
-
Save qickstarter/5932108 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# each_with_objectの使い方 | |
# ---------------------------------------- | |
# 1. 簡単な使い方 | |
each_with_objectは、引数のメモ化用オブジェクトを渡して、最後に必ず返す。 | |
alpha_1 = [] | |
('a'..'z').each do |str| | |
alpha_1 << str.upcase | |
end | |
alpha_2 = ('a'..'z').each_with_object([]) do |str, memo| | |
memo << str.upcase | |
end | |
p alpha_1 == alpha_2 #=> true | |
# ---------------------------------------- | |
# 2. injectと比べて理解する | |
hash_list = ["downcase", "2", "upcase"] | |
res_1 = hash_list.inject({}) do |hash, str| | |
hash[str] = str.upcase unless str.match(/\d/) | |
hash #=> injectは必ず値を返さないと、メモ化されない | |
end | |
## each_with_objectだと一行無くなる | |
res_2 = hash_list.each_with_object({}) do |str, hash| | |
hash[str] = str.upcase unless str.match(/\d/) | |
end | |
p res_1 == res_2 #=> true | |
# ---------------------------------------- | |
# 3. each_with_objectの注意点 | |
list = (1..5) | |
## each_with_objectでは数値などは使えない。hashやarrayのようにメモ化出来ないから。 | |
p list.reduce(:+) #=> 15 | |
p list.inject { |sum, i| sum += i } #=> 15 | |
p list.inject(0) { |sum, i| sum += i } #=> 15 | |
p list.each_with_object(0) { |i, sum| sum += i } #=> 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment