Reputation: 43
I am having a following hash array
A = [{"name" => ["xx"], "status" => ["true"]}, {"name" => ["yy"], "status" => ["true"]}
I tried following code to remove the square brackets
A.to_s.gsub("\\[|\\]", "")
also tried with code
p A.map { |hash| hash.each_with_object({}) { |(k, v), hash| hash[k] = v.first } }
but its not working.
How I remove the square brackets to get following output
A = [{"name" => "xx", "status" => "true"}, {"name" => "yy", "status" => "true"}
Kindly assist
Upvotes: 2
Views: 714
Reputation: 33420
Since they're strings inside arrays, the [] is the representation Ruby does of it. Try accessing the first element for each key's value in those hashes:
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"}]
Depending on your Ruby version, you might not have transform_values available. A simple each_with_object
would work similarly in that case:
p a.map { |hash| hash.each_with_object({}) { |(k, v), hash| hash[k] = v.first } }
# [{"name"=>"xx", "status"=>"true"}, {"name"=>"yy", "status"=>"true"}]
Upvotes: 3