Split an array of object by first letter

Hi,
I have an array of brands and I need to split this array by brand name
first letter. How can I do that?

Greg

···

--
Posted via http://www.ruby-forum.com/.

Greg Ma wrote:

Hi,
I have an array of brands and I need to split this array by brand name
first letter. How can I do that?

["fz", "yt", "fu", "za", "zw", "yo", "zb"].group_by {|s|s[0,1]}
=> {"y"=>["yt", "yo"], "z"=>["za", "zw", "zb"], "f"=>["fz", "fu"]}

Joel is right on. My addition below shows that (a) this works not just
for two-letter words, and (b) if you're using Ruby 1.9, you can use a
slightly simpler syntax:

[ "foo", "bar", "flim", "bork", "cow" ].group_by{ |name| name[0] }
#=> {"f"=>["foo", "flim"], "b"=>["bar", "bork"], "c"=>["cow"]}

Note that case matters, but you can make it irrelevant:

[ "foo", "bar", "Flim", "bork" ].group_by{ |name| name[0] }
#=> {"f"=>["foo"], "b"=>["bar", "bork"], "F"=>["Flim"]}

[ "foo", "bar", "Flim", "bork" ].group_by{ |name| name[0].downcase }
#=> {"f"=>["foo", "Flim"], "b"=>["bar", "bork"]}

And finally, just for the love of monkeypatching:

class String
  def first_letter
    self[0].downcase
  end
end

class Array
  def alphabetical
    Hash[ group_by{|s|s.first_letter}.sort_by{|c,a|c} ]
  end
end

[ "foo", "bar", "Flim", "bork" ].alphabetical
#=> {"b"=>["bar", "bork"], "f"=>["foo", "Flim"]}

···

On Jun 10, 1:45 pm, Joel VanderWerf <joelvanderw...@gmail.com> wrote:

> I have an array of brands and I need to split this array by brand name
> first letter. How can I do that?

["fz", "yt", "fu", "za", "zw", "yo", "zb"].group_by {|s|s[0,1]}
=> {"y"=>["yt", "yo"], "z"=>["za", "zw", "zb"], "f"=>["fz", "fu"]}