0

I want to remove the spaces in the key value in the hashes

output = [
  {"first name"=> "george", "country"=>"Australia"},
  {"second name"=> "williams", "country"=>"South Africa"},
  {"first name"=> "henry", "country"=>"US"}]

I was able to manage when only one hash was there inside the array with the following code

    Array.wrap({}.tap do |hash|
     output.each do |key|
      key.each do |k, v|
       hash[k.gsub(" ","_")] = v
      end
     end
    end)

Please help me to modify the array containing more than one hash.

Note: the output value is dynamic that we cannot hardcode the hash key in the code.

2
  • The mentioned array didn't work well with the code Commented Mar 31, 2016 at 14:10
  • It worked only with [{"first name" => "George", "country" => "Australia"}] Commented Mar 31, 2016 at 14:14

3 Answers 3

1

If hash is not nested - you can simply

output.map{|h| h.each_pair.map{|k,v| [k.gsub(' ', '_'), v]}.to_h }
Sign up to request clarification or add additional context in comments.

3 Comments

The whole hash is array wrapped
Please note that it is an array of hashes
user3636388, I expect @Vasfed realized that, but the essence of the question is how to "remove spaces" in a hash's keys. Once you know how to do it for one hash, you obviously would just map the array, converting each (hash) element. The question would have been better had you confined it to a single hash. You are new to Ruby, however, so it's understandable that you didn't do that.
0

Here's code that will change the spaces to underscores for each key in a hash:

output.flat_map { |h| h.map { |key, v| { key.gsub(" ", "_") => v } } }
=> [{"first_name"=>"george"}, {"country"=>"Australia"}, {"second_name"=>"williams"}, {"country"=>"South Africa"}, {"first_name"=>"henry"}, {"country"=>"US"}]

Comments

0

You cannot modify a hash's keys. You must remove the unwanted key and add a new one. Here's a way of doing both operations in one step (see the doc Hash#delete):

def convert(h) 
  h.keys.each { |k| (h[k.tr(' ','_')] = h.delete(k)) if k =~ /\s/ }
  h
end

Hence:

output.map { |h| convert h }
  #=> [{"country"=>"Australia", "first_name"=>"george"},
  #    {"country"=>"South Africa", "second_name"=>"williams"},
  #    {"country"=>"US", "first_name"=>"henry"}]

I've used the method String#tr to convert spaces to underscores, but you could use String#gsub as well. Also, you could write k.include?(' ') rather than k =~ /\s/.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.