可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have this:
hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
and I want to get to this: [["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?
回答1:
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
回答2:
I would use:
hash.map { |key, value| value }
回答3:
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.
回答4:
hash = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]
回答5:
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"]]
回答6:
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)