Ruby 数组与哈希操作全解析
1. 数组操作
在 Ruby 中,数组是一种非常常用的数据结构,它提供了丰富的操作方法。
1.1 提取元素
Array#reject! 方法可以移除数组中符合代码块条件的元素,但它不会返回被移除的元素。为了实现类似 Enumerable#find_all 的破坏性操作,可以自定义 extract! 方法:
class Array
def extract!
ary = self.dup
self.reject! { |x| yield x }
ary - self
end
end
a = ("a".."h").to_a
a.extract! { |x| x < "e" && x != "b" } # => ["a", "c", "d"]
a # => ["b", "e", "f", "g", "h"]
此外,还可以定义 grep_extract! 方法,它可以破坏性地近似 Enumerable#grep 的行为:
class Array
def grep_extract!(re)
extract! { |x| re.match(x) }
超级会员免费看
订阅专栏 解锁全文
8

被折叠的 条评论
为什么被折叠?



