Split an array of object by first letter

G

Greg Ma

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
 
J

Joel VanderWerf

Greg said:
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"]}
 
P

Phrogz

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"]}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,150
Messages
2,570,853
Members
47,394
Latest member
Olekdev

Latest Threads

Top