首页 > 解决方案 > 代码块中的两条垂直线和 super.select 是什么意思?

问题描述

以下实际上是什么意思?

def method
  super.select { |a| a.meets_condition? || true }
end

我特别挣扎|| 在这种情况下。使用搜索引擎很难找到此类问题的答案。

做什么的super.select

如果删除“|| true”部分,该方法会做什么?

标签: ruby

解决方案


这是一段奇怪的代码,但这就是它的作用:

您正在定义一个名为method

特殊方法super意味着在父(超)类上调用相同的命名方法。

您正在获取 的结果super,它必须是“可枚举”对象,例如数组或散列并调用select该对象

select遍历可枚举对象(假设它是一个数组)并使用每个元素调用块。通常它用于从数组中过滤(或选择)一些对象。每次调用该块时,它都会返回一个真值或假值。如果为真,则该元素将保留在结果数组中。如果是虚假的,则将其丢弃。

好的,所以这个数组的每个元素都将在其上执行:

a.meets_condition? || true

这很奇怪,因为这要做的是调用meets_condition?数组的元素,如果它返回一个真值,那么该元素 (a) 将保留在数组中。

但是如果a.meets_condition?是假的呢?

然后我们继续or(双管)的下一部分并这样做。

返回真。

所以基本上这个表达式将返回你传入的数组的副本。

让我们把这个例子变成一个实际的工作例子:

class RandomDigit
  # gives you a object containing a random digit between 0 and 9
  def initialize
    @n = rand(10)
  end
  def meets_condition?  # returns true if @n is even 
    @n % 2 == 0 
  end
end

class TheParentClass
  def method
    # returns array of 4 random digits (between 0 and 9)
    [RandomDigit.new, RandomDigit.new, RandomDigit.new, RandomDigit.new]
  end
end

class TheChildClass < TheParentClass
  def method
    # super means we are calling TheParentClass.method
    # select will try each element of the the array 
    # and builds a new array, with elements that returned true
    # but the trouble is || true means its always going to return true
    super.select { |a| a.meets_condition? || true }
  end
end

puts TheChildClass.new.method # -> returns 4 random digits

您可以单击此链接运行代码并查看它的工作情况

http://opalrb.com/try/?code:class%20RandomDigit%0A%20%20def%20initialize%0A%20%20%20%20%40n%20%3D%20rand(10)%0A%20% 20end%0A%20%20def%20meets_condition%3F%0A%20%20%20%20%40n%20%25%202%20%3D%3D%200%20%23%20returns%20true%20if%20% 40n%20is%20even%0A%20%20end%0Aend%0A%0Aclass%20TheParentClass%0A%20%20def%20method%0A%20%20%20%20%23%20returns%204%20random%20digits%20(在%200%20和%209之间)%0A%20%20%20%20%5BRandomDigit.new%2C%20RandomDigit.new%2C%20RandomDigit.new%2C%20RandomDigit.new%5D%0A%20%20end%0Aend %0A%0Aclass%20TheChildClass%20%3C%20TheParentClass%0A%20%20def%20method%0A%20%20%20%20super.select%20%7B%20%7Ca%7C%20a.meets_condition%3F%20 %7C%7C%20true%20%7D%0A%20%20end%0Aend%0A%0Aputs%20TheChildClass.new.method

为了清楚起见,这里唯一没有真正意义的是|| true零件。

否则,这将是您正在定义一个新类,并且您正在稍微更改其行为,method以便它的工作方式类似于原始类,method但会过滤掉元素。

通常你可能会看到类似a.question_1? || a.question_2?

哪个会尝试 question_1?如果它返回true,那么我们就完成了。

如果它不返回 true,请尝试 question_2。

这是因为||是控制操作流......如果第一部分已经为真,则第二部分不会被执行。

&&恰恰相反,因为除非第一部分为真,否则第二部分不会被执行。


推荐阅读