使用flatten
、select
和regexp
的组合来处理数字\d
:
=> a = {
a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}
=> a.values.flatten.select { |x| x =~ /\d/ }.map(&:to_i)
#> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
使用flat_map
、map
和( )
的另一种方式:
使用括号来更明确地访问结构内部
=> a = {
a: [ ["c", "1"],["d","2"],["e","3"],["f","4"] ],
b: [ ["g","5"],["h","6"],["i","7"],["j","8"] ],
c: [ ["k","9"],["l","10"],["m","11"],["n","12"] ]
}
=> a.flat_map { |_, (n, z, i, x)| [n, z, i, x] }.map { |_, i| i.to_i }
#> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
h.to_s.scan(/\d+/).map(&:to_i).sort
。 - Cary Swovelandh = { a:...}
)很有帮助,这样读者在回答和评论中引用这些变量时无需定义它们。 - Cary Swoveland