簡體   English   中英

根據 my_times 定義 my_each

[英]defining my_each in terms of my_times

我正在閱讀The Well-Grounded Rubyist並且遇到了一個額外的信用挑戰,沒有答案。

class Array
  def my_each
    c = 0
    until c == size
      yield(self[c])
      c += 1
    end
    self
  end
end

給出了一個使用my_times創建my_each的示例

class Array
  def my_each
    size.my_times do |i|
      yield self[i]
    end
    self
  end
end

許多 Ruby 的迭代器都建立在each迭代器之上,而不是相反。

鑒於上述my_each ,我如何在my_times的實現中使用它?

為了清楚起見,之前給出了一個my_times實現的示例:

class Integer
  def my_times
    c = 0
    until c == self
      yield(c)
      c += 1
    end
    self
  end
end

5.my_times { |e| puts "The block just got handed #{e}." }

所以看起來這個問題最肯定意味着在my_each的實現中使用my_times

要使用my_each實現my_times ,您需要做的就是在看起來像[0, 1, ..., (x - 1)]的數組上調用my_each ,其中xself (整數):

class Integer
  def my_times(&block)
    (0...self).to_a.my_each do |n|
      yield n
    end
    self
  end
end

PS 如果您在 Enumerable 上定義my_each而不是 Array (就像“真正的” each ),您可以從上面的第三行中刪除to_a並直接在 Range 上迭代,而不是先將 Range 轉換為 Array 。

編輯:我剛剛注意到Jordan使用了...而不是..產生了正確的輸出; 有關范圍差異的更多詳細信息,請參閱此答案 我在下面更新了我的答案。

我的賬號太新,無法評論喬丹的解決方案; 我看到這是大約一年前發布的,但我目前正在閱讀The Well-Grounded Rubyist並想對解決方案發表評論。

以與Jordan類似的方式接近它但發現輸出與; my_timesmy_times Rubyist實現,產生:

puts 5.my_times { |i| puts "I'm on iteration # {i}!" }
I'm on iteration 0!
I'm on iteration 1!
I'm on iteration 2!
I'm on iteration 3!
I'm on iteration 4!

Jordan 的解決方案輸出:

 puts 5.my_times { |i| puts "I'm on iteration # {i}!" } I'm on iteration 0! I'm on iteration 1! I'm on iteration 2! I'm on iteration 3! I'm on iteration 4! I'm on iteration 5!

我使用了一個幻數來匹配The Well-Grounded Rubyist輸出[參見 Jordan 的解決方案,使用...而不是..這消除了對幻數的需要]

class Integer
  def my_times
    (0..(self-1)).to_a.my_each do |n|
      yield n
    end
    self
  end
end

為了實現 my_times,我們需要一個數組來發送 my_each 消息。 在這本書的那個時候,我認為范圍沒有被涵蓋,所以我在不使用范圍的情況下實現了。 這是解決方案:

require_relative "my_each"
class Integer
  def my_times
    array = Array.new(self)
    c = 0
    array.my_each do
      array[c] = c
      yield(c)
      c += 1
    end
    self
  end
end

我縮短了 dwyd 的實現以提供一個塊而不是使用 do..end。

class Integer
  def my_times
    (0...self).to_a.my_each { |i| yield i }
  end
end

另外,我認為您不需要執行self-1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM