试图写我自己的一切? Ruby中的方法 [英] Trying to write my own all? method in Ruby

查看:53
本文介绍了试图写我自己的一切? Ruby中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法称为 all? 中的数字.

There is a method called all? in Enumerable.

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

I'm trying to learn all the methods of Enumberable's library by writing them myself.

到目前为止,这是我为all?方法所提出的.我有点理解,但是在尝试将初始化的值传递给我的方法时感到困惑.

This is what I've come up so far for the all? method. I sorta understand it but I got stumped when trying to pass initialized values to my method.

EDIT 作为记录,我知道我拥有的enum方法不是正确的方法,即它是硬编码数组.这是为了自学的目的.我只是想弄清楚如何将初始化值传递给 my 全部?方法.这就是为什么我首先编写枚举,以确保它确实起作用的原因.请不要把这堂课当作字面的福音.谢谢.

EDIT for the record, I'm aware that enum method that I have is not the right way ie, it's hard-coded array. This is for self-learning purposes. I'm just trying to figure out how to pass the initialized values to my all? method. That's why I wrote enum in the first place, to see that it is working for sure. Please don't take this class as a literal gospel. Thank you.

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? 

推荐答案

我不确定您为什么根本需要枚举? Enumerable是数组中包含的模块,因此,如果您对此不熟悉,我建议您阅读Ruby中的模块和混入".

I'm not sure why you need enum at all? Enumerable is a module included in array, so if you're not familiar with this I recommend you read about "modules and mix-ins" in Ruby.

all?的工作原理是将每个数组元素传递给块.如果有任何元素(至少为1),该块为其返回false,则all?的计算结果为false.尝试分析此代码:

all? works simply by passing EACH of the array elements to the block. If there is ANY element (at least 1) for which the block returns false, then all? evaluates to false. Try analyzing this code:

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

这篇关于试图写我自己的一切? Ruby中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆