简体   繁体   English

Ruby Hash到值数组

[英]Ruby Hash to array of values

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? 有什么建议?

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 doc在这里

我会用:

hash.map { |key, value| value }
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. Enumerable#collect接受一个块,并在枚举的每个元素上返回一次运行块的结果数组。 So this code just ignores the keys and returns an array of all the values. 所以这段代码只是忽略了键并返回了所有值的数组。

The Enumerable module is pretty awesome. Enumerable模块非常棒。 Knowing it well can save you lots of time and lots of code. 了解它可以为您节省大量时间和大量代码。

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

It is as simple as 它很简单

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

this will return a new array populated with the values from hash 这将返回一个填充了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"]]

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. &调用对象上的to_proc ,并将其作为块传递给方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM