Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Generate all two letter words

Tags:

arrays

ruby

I am trying to generate a array containing all two letter word combinations.

What would be the best way to generate it.

Could someone help me out?

like image 979
RailsSon Avatar asked Mar 06 '11 19:03

RailsSon


2 Answers

As steenslag points out, the quickest way is

('aa'..'zz').to_a

If your alphabet isn't 'a' through 'z', though, you can use Array#repeated_combination:

alphabet = %w[А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я]
alphabet.repeated_combination(2).map(&:join) # => ["AA", "AБ", ...]

Or, as Mladen points out:

alphabet.product(alphabet).map(&:join)

Note: repeated_combination is available in Ruby 1.9.2 or with require 'backports/1.9.2/array/repeated_combination' from my backports gem.

like image 131
Marc-André Lafortune Avatar answered Sep 28 '22 08:09

Marc-André Lafortune


('aa'..'zz').to_a

Converts a Range to an Array.

like image 25
steenslag Avatar answered Sep 28 '22 08:09

steenslag