Thursday, May 29, 2008

Rails: String to Hash




Given a string like " 234,456 , 678 , 4 " I want to produce Hash object {456=>true, 678=>true, 234=>true, 4=>true}

Solution:
  1.  a = "   234,456 , 678  , 4   "

  2.  b = a.split(%r{\s*,\s*}).inject(Hash.new) {|h, e| h.merge({e.to_i=>true}) }