ruby-on-railsarraysrubyhash

Best way of transforming values in array of hashes (performance)


Given:

data = [
  {"votable_id"=>1150, "user_ids"=>"1,2,3,4,5,6,"},
  {"votable_id"=>1151, "user_ids"=>"55,66,34,23,56,7,8"}
]

This is the expected result. Array should have first 5 elements.

data = [
  {"votable_id"=>1150, "user_ids"=>["1","2","3","4","5"]},
  {"votable_id"=>1151, "user_ids"=>["55","66","34","23","56","7",8"]}
]

This is what I tried :

data.map{|x| x['user_ids'] = x['user_ids'].split(',').first(5)}

Any other optimized solution ?


Solution

  • You can also use .map and .tap like this

    data.map do |h|
     h.tap { |m_h| m_h["user_ids"]= m_h["user_ids"].split(',').first(5)}
    end