1

I'm reading The Well-Grounded Rubyist and have come across an extra credit challenge to which there is no answer.

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

An example is given of creating a my_each with my_times

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

With the point that many of Ruby's iterators are built on top of each and not the other way around.

Given the above my_each, how could I use it in an implementation of my_times?

To make it clear, an example of a my_times implementation was given before:

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}." }

So it would seem that the question most certainly implies using my_each in an implementation of my_times.

4

3 回答 3

4

要实现my_timesusing my_each,您需要做的就是调用my_each一个看起来像 的数组[0, 1, ..., (x - 1)],其中xself(整数):

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

PS 如果您my_each在 Enumerable 而不是 Array 上定义(如 "real" each),您可以to_a从上面的第三行中删除并直接遍历 Range,而不是先将 Range 转换为 Array。

于 2015-05-22T17:57:36.380 回答
3

为了实现 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
于 2017-05-02T21:12:50.927 回答
2

编辑:我刚刚注意到Jordan使用...而不是..生成正确的输出;有关范围差异的更多详细信息,请参阅此答案。我在下面更新了我的答案。

我的帐户太新,无法评论Jordan的解决方案;我看到这是大约一年前发布的,但我目前正在阅读The Well-Grounded Rubyist并想对解决方案发表评论。

我以与Jordan类似的方式接近它 但发现输出与; Well-Grounded Rubyist实现产生my_times

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
于 2016-05-20T19:23:50.147 回答