I have a ruby hash a
as follows:
a = {
"module" => 'students',
"data" => [
{
"age" => 12,
"uid" => 'sd3wrew'
},
{
"age" => 10,
"uid" => '43e43r'
},
{
"age" => 10,
"uid" => 'ft34f'
}
]
}
I want to collect all uid
from above hash and get an array like:
b = ['sd3wrew', '43e43r', 'ft34f']
so, I have code to do this, which loop through it.
b = []
a['data'].each do |e|
b << e['uid']
end
Is there anyway to achieve this result without looping each
and much concise?
You're looking for the functional programming concept called "map."
b = a['data'].collect {|e| e['uid'] }
# or
b = a['data'].map {|e| e['uid'] }
如果key与uid
相等,它将在哈希中打印每个键:
b = a["data"].each_key { |e| print e if e='uid' }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.