从数组ruby rails中的哈希值中检索特定值

obi*_*obi 15 ruby arrays hash ruby-on-rails

Noob在这里提问!

我有一个带有哈希的数组,如下所示:

arr = [{id: 1, name: "Pedro"},{id: 2, name: "Pablo"}]
Run Code Online (Sandbox Code Playgroud)

并希望有这样的数组:

ids = [1,2]
Run Code Online (Sandbox Code Playgroud)

我调查使用地图或选择这样:

ids = arr.each.select{|k,v| "id"==k}
Run Code Online (Sandbox Code Playgroud)

但我无法弄明白.

Nik*_* B. 29

请尝试以下方法:

ids = arr.map { |x| x[:id] }
Run Code Online (Sandbox Code Playgroud)

  • 为什么像'arr.map(&:[:id])`这样的东西不起作用? (4认同)
  • @Cycle:几个原因:首先`:[`不是符号,因为`[`不是有效的标识符.其次,你不能将`&`技巧与方法参数结合使用,因为精确的语法是`method(arg1,arg2,...,&x)`,其中x是一个表达式,它的计算结果为` to_proc`方法.调用`to_proc`方法,并将生成的`Proc`对象作为块参数传递给`method`. (2认同)