coyote_rey coyote_rey - 1 year ago 107
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=>'', :id=>1},
{:firstname=>'Michael', :lastname=>'Rodriguez', :email=>'', :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 Source! do |hash|
  hash.each_with_object({}) do |(k, v), h|
    h[k] = v.is_a?(String) ? v.to_s.split(' ').first : v
#=>[{:firstname=>"Anne", :lastname=>"Hook", :email=>"", :id=>1}, {:firstname=>"Michael", :lastname=>"Rodriguez", :email=>"", :id=>2}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download