红宝石 |结构过滤器()函数
filter()是 Ruby 中的一个内置方法,它返回一个数组,其中包含来自 struct 的成员值,该值返回给定块的真值。
Syntax: filter {|obj| block }
Parameters: The function accepts a single parameter block which specifies the condition.
Return Value: It returns member value from struct to block and an array is returned.
示例 1 :
# Ruby program for filter method in struct
# Initialize struct
Num = Struct.new(:a, :b, :c, :d)
# Initialize numbers
l = Num.new(12, 22, 13, 44)
# Filter used
l.select {|v| v.even? }
输出:
[12, 22, 44]
示例 2 :
# Ruby program for filter method in struct
# Initialize struct
Num = Struct.new(:a, :b, :c, :d)
# Initialize numbers
l = Num.new(12, 22, 13, 44)
# Filter used
l.select {|v| v.odd? }
输出:
[13]