["xx"], "status" => ["true"]}, {"name" => ["yy"], "status" => ["true"]} 我尝试-6ren">
gpt4 book ai didi

ruby - 从散列数组中删除方括号以获取值

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:40 25 4
gpt4 key购买 nike

我有一个哈希数组

A = [{"name" => ["xx"], "status" => ["true"]}, {"name" => ["yy"], "status" => ["true"]}

我尝试按照以下代码删除方括号

A.to_s.gsub("\\[|\\]", "")

也尝试过代码

p A.map { |hash| hash.each_with_object({}) { |(k, v), hash| hash[k] = v.first } }

但它不起作用。

我如何删除方括号以获得以下输出

A = [{"name" => "xx", "status" => "true"}, {"name" => "yy", "status" => "true"}

请帮忙

最佳答案

因为它们是数组中的字符串,所以 [] 是 Ruby 对它的表示。尝试访问这些散列中每个键值的第一个元素:

a = [{"name" => ["xx"], "status" => ["true"]}, {"name" => ["yy"], "status" => ["true"]}]
p a.map { |hash| hash.transform_values(&:first) }
# [{"name"=>"xx", "status"=>"true"}, {"name"=>"yy", "status"=>"true"}]

根据您的 Ruby 版本,您可能没有可用的 transform_values。在这种情况下,一个简单的 each_with_object 的工作方式类似:

p a.map { |hash| hash.each_with_object({}) { |(k, v), hash| hash[k] = v.first } }
# [{"name"=>"xx", "status"=>"true"}, {"name"=>"yy", "status"=>"true"}]

关于ruby - 从散列数组中删除方括号以获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53214287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com