Ruby - Generate all two letter words

99封情书 提交于 2019-12-05 00:11:25

问题


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?


回答1:


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.




回答2:


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

Converts a Range to an Array.



来源:https://stackoverflow.com/questions/5212884/ruby-generate-all-two-letter-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!