Skip to content

Instantly share code, notes, and snippets.

@YanLinGitHub
Created October 24, 2018 14:04
Show Gist options
  • Save YanLinGitHub/d14468fe2bff9beadc25fca5a5cbb4e1 to your computer and use it in GitHub Desktop.
Save YanLinGitHub/d14468fe2bff9beadc25fca5a5cbb4e1 to your computer and use it in GitHub Desktop.
# 印出 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
@kaochenlong
Copy link

最後一題不是用 puts 把結果印出來,因為原本的 select 方法是把結果「收集」起來變成一個新的陣列,所以可以這樣寫:

class Array
  def my_select
    result = []
    self.each do |i|
      result << i if yield(i)
    end
    result
  end
end

其它題沒什麼問題

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment