-
-
Save YanLinGitHub/d14468fe2bff9beadc25fca5a5cbb4e1 to your computer and use it in GitHub Desktop.
This file contains 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
# 印出 1 到 100 之間所有單數 | |
p [*1..100].select { |i| i.odd? } | |
# 印出 1 到 100 之間所有單數的總和 | |
p [*1..100].select { |i| i.odd? }.sum | |
# 改良版土砲 times 方法 | |
class Integer | |
def my_times | |
i = 0 | |
while i < self | |
yield(i) | |
i += 1 | |
end | |
end | |
end | |
5.my_times { |i| puts i } # 印出數字 0 到 4 | |
# 土砲 select 方法 | |
class Array | |
def my_select | |
self.each do |i| | |
puts i if yield(i) | |
end | |
end | |
end | |
[1, 2, 3, 4, 5].my_select { |i| i.odd? } # 印出單數 1、3、5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
最後一題不是用 puts 把結果印出來,因為原本的
select
方法是把結果「收集」起來變成一個新的陣列,所以可以這樣寫:其它題沒什麼問題