Ruby Hash to array of values

后端 未结 6 423
太阳男子
太阳男子 2020-12-04 09:32

I have this:

hash  = { \"a\"=>[\"a\", \"b\", \"c\"], \"b\"=>[\"b\", \"c\"] } 

and I want to get to this: [[\"a\",\"b\",\"c\"],[

相关标签:
6条回答
  • 2020-12-04 09:52

    I would use:

    hash.map { |key, value| value }
    
    0 讨论(0)
  • 2020-12-04 09:53
    hash.collect { |k, v| v }
    #returns [["a", "b", "c"], ["b", "c"]] 
    

    Enumerable#collect takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.

    The Enumerable module is pretty awesome. Knowing it well can save you lots of time and lots of code.

    0 讨论(0)
  • 2020-12-04 09:59

    There is also this one:

    hash = { foo: "bar", baz: "qux" }
    hash.map(&:last) #=> ["bar", "qux"]
    

    Why it works:

    The & calls to_proc on the object, and passes it as a block to the method.

    something {|i| i.foo }
    something(&:foo)
    
    0 讨论(0)
  • 2020-12-04 10:02

    It is as simple as

    hash.values
    #=> [["a", "b", "c"], ["b", "c"]]
    

    this will return a new array populated with the values from hash

    if you want to store that new array do

    array_of_values = hash.values
    #=> [["a", "b", "c"], ["b", "c"]]
    
    array_of_values
     #=> [["a", "b", "c"], ["b", "c"]]
    
    0 讨论(0)
  • 2020-12-04 10:14
    hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
    hash.values #=> [["a","b","c"],["b","c"]]
    
    0 讨论(0)
  • 2020-12-04 10:15

    Also, a bit simpler....

    >> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
    => {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
    >> hash.values
    => [["a", "b", "c"], ["b", "c"]]
    

    Ruby doc here

    0 讨论(0)
提交回复
热议问题