ruby数组和Hash直接的转换
Ruby Hash to array of values
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
Get a value from an array of hashes in ruby
The select statement will return all the hashes with the key 13.
If you already know which hash has the key then the below code will give u the answer.
ary[1][13]
However if you are not sure which of your hashes in the array has the value, then you could do the following:
values = ary.map{|h| h[13]}.compact
Values will have the value of key 13 from all the hashes which has the key 13.
Ruby convert an Array to Hash values with specific keys
You can use #zip
your_array = ["12", "21", "1985"] keys = ['month', 'day', 'year'] keys.zip(your_array).to_h
Convert hash to array of hashes
Leveraging Array#transpose and Array#to_h
keys = list.keys list.values.transpose.map { |v| keys.zip(v).to_h }
Collect specific values from an array of hashes
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.
Of course, a value can be any object - string, method, nil, number, object. So, only after create, we can know that is saved in our hash. For this reason when trying to get all key:
data.keys # => ["etag", "items"]
There is no any nested key. So finding value by missing key return nil.
To select all videoId you must do something like this:
data["items"].map { |item| item["snippet"]["resourceId"]["videoId"] }.compact
Also, you can update Hash class as there:
class Hash def deep_find(key, object=self, found=nil) if object.respond_to?(:key?) && object.key?(key) return object[key] elsif object.is_a? Enumerable object.find { |*a| found = deep_find(key, a.last) } return found end end end
And then run
data["items"].map { |item| item.deep_find('videoId') }
That method avoids the error when the json will have a variable structure.
Convert array of hashes to array
a=[{:code=>"404"}, {:code=>"302"}, {:code=>"200"}] puts a.map{|x|x.values}.flatten.inspect
output
["404", "302", "200"]
ruby: how to convert hash into array
try this:
{0=>0.07394653730860076, 1=>0.0739598476853163, 2=>0.07398647083461522}.to_a #=> [[0, 0.07394653730860076], [1, 0.0739598476853163], [2, 0.07398647083461522]]
Creating a Hash with values as arrays and default value as empty array
Lakshmi is right. When you created the Hash using Hash.new([]), you created one array object.
Hence, the same array is returned for every missing key in the Hash.
That is why, if the shared array is edited, the change is reflected across all the missing keys.
Using:
Hash.new { |h, k| h[k] = [] }
Creates and assigns a new array for each missing key in the Hash, so that it is a unique object.
阅读量: 643
发布于:
修改于:
发布于:
修改于: