试着写我自己的全部? Ruby中的方法

时间:2014-10-02 20:56:49

标签: ruby methods enumerable

Enumerable中有一个名为all?的方法。

我正在尝试通过自己编写来学习Enumberable库的所有方法。

这是我到目前为止为all?方法提出的。我理解它,但是在尝试将初始值传递给我的方法时我感到难过。

记录的

EDIT ,我知道我所拥有的枚举方法不是正确的方式,即它是硬编码数组。这是为了自学目的。我只想弄清楚如何将初始值传递给 my all?方法。这就是为什么我首先写了enum,看它确实有效。请不要将这门课作为字面福音。谢谢。

class LearningMethods

  def initialize(values)
    @values = values
  end

  def enum
    array = [10, 3, 5]
  end


  def all?(a)
    yield(a)
  end

end

c = LearningMethods.new([10, 3, 5])
p c.enum.all? {|x| x >= 3 } #this works

p c.all?(10) { |x| x >= 3 } #this works

p c.all?(@values) { |x| x >= 3 } #this doesn't work. Why not? And how do I pass the initialized values? 

1 个答案:

答案 0 :(得分:0)

我不确定你为什么需要枚举? Enumerable是一个包含在数组中的模块,所以如果你不熟悉这个,我建议你阅读" modules和mix-ins"在Ruby中。

all?只需将每个数组元素传递给块即可。如果存在块返回false的任何元素(至少为1),则all?的计算结果为false。尝试分析此代码:

class MyAllImplementation
  def initialize(array)
    @array = array
  end

  def my_all?
    @array.each do |element| # for each element of the array
      return true unless block_given? # this makes sure our program doesn't crash if we don't give my_all? a block.
      true_false = yield(element) # pass that element to the block
      return false unless true_false # if for ANY element the block evaluates to false, return false
    end
    return true # Hooray! The loop which went over each element of our array ended, and none evaluted to false, that means all elements must have been true for the block.
  end
end


a = MyAllImplementation.new([1,2,3])
p a.my_all? { |x| x > 0 } #=> true
p a.my_all? { |x| x > 1 } # false, because 1 is not bigger than 1, it's equal to 1