Ruby Hash 到值数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9560335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:51:41  来源:igfitidea点击:

Ruby Hash to array of values

rubyarrayshash

提问by tbrooke

I have this:

我有这个:

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

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

我想解决这个问题: [["a","b","c"],["b","c"]]

This seems like it should work but it doesn't:

这似乎应该有效,但它没有:

hash.each{|key,value| value}
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]} 

Any suggestions?

有什么建议?

回答by Ray Toal

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

Ruby 文档在这里

回答by Michael Durrant

I would use:

我会用:

hash.map { |key, value| value }

回答by jergason

hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]] 

Enumerable#collecttakes 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.

Enumerable#collect接受一个块,并返回在可枚举的每个元素上运行该块一次的结果数组。所以这段代码只是忽略键并返回所有值的数组。

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

Enumerable模块非常棒。了解它可以为您节省大量时间和大量代码。

回答by mrded

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

回答by Melissa Quintero

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"]]

回答by karlingen

There is also this one:

还有这个:

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

Why it works:

为什么有效:

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

对对象的&调用to_proc,并将其作为块传递给方法。

something {|i| i.foo }
something(&:foo)