ruby - 代码块中的两条垂直线和 super.select 是什么意思?
问题描述
以下实际上是什么意思?
def method
super.select { |a| a.meets_condition? || true }
end
我特别挣扎|| 在这种情况下。使用搜索引擎很难找到此类问题的答案。
做什么的super.select
?
如果删除“|| true”部分,该方法会做什么?
解决方案
这是一段奇怪的代码,但这就是它的作用:
您正在定义一个名为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
您可以单击此链接运行代码并查看它的工作情况
为了清楚起见,这里唯一没有真正意义的是|| true
零件。
否则,这将是您正在定义一个新类,并且您正在稍微更改其行为,method
以便它的工作方式类似于原始类,method
但会过滤掉元素。
通常你可能会看到类似a.question_1? || a.question_2?
哪个会尝试 question_1?如果它返回true,那么我们就完成了。
如果它不返回 true,请尝试 question_2。
这是因为||
是控制操作流......如果第一部分已经为真,则第二部分不会被执行。
&&
恰恰相反,因为除非第一部分为真,否则第二部分不会被执行。
推荐阅读
- java - 无法让 mockito 模拟公共类的公共方法
- ruby-on-rails - 如何输出更多信息来记录此错误?
- apex - 有没有办法防止方括号被插入到我的字符串中?
- javascript - 如何使用回调函数修复错误?
- uwp - 通用 Windows App Store 试用许可剩余时间不正确
- r - 创建一个绘图以显示值是否匹配
- linux - 如何在单进程模式下运行 tensorflow?
- java - 当我在手机上运行应用程序时,我的物品都搞砸了
- google-cloud-firestore - Cloud Firestore 安全规则匹配集合?
- ios - 在 iOS 上弃用 Google Places