coyote_rey coyote_rey - 2 months ago 8
Ruby Question

Remove everything after first whitespace in array

I have an array of hashes with some values inside the hashes containing spaces. I would like to run through every array element and every value within the hashes to remove any spaces and the following characters past the space. An example of my data would be

arrayHash = [{:firstname=>'Anne Marie', :lastname=>'Hook', :email=>'test@test.com', :id=>1},
{:firstname=>'Michael', :lastname=>'Rodriguez', :email=>'test2@test.com', :id=>2}]


So for example on the firstname key, I would like to take 'Anne Marie' and reduce it to just 'Anne', and do the same for every element in this array.

Answer
arrayHash.map! do |hash|
  hash.each_with_object({}) do |(k, v), h|
    h[k] = v.is_a?(String) ? v.to_s.split(' ').first : v
  end
end
#=>[{:firstname=>"Anne", :lastname=>"Hook", :email=>"test@test.com", :id=>1}, {:firstname=>"Michael", :lastname=>"Rodriguez", :email=>"test2@test.com", :id=>2}]