生成所有字母和数字的数组

使用红宝石,是否有可能使一个数组的每个字母在字母表和0-9容易?

82079 次浏览

for letters or numbers you can form ranges and iterate over them. try this to get a general idea:

("a".."z").each { |letter| p letter }

to get an array out of it, just try the following:

("a".."z").to_a
[*('a'..'z'), *('0'..'9')] # doesn't work in Ruby 1.8

or

('a'..'z').to_a + ('0'..'9').to_a

or

(0...36).map{ |i| i.to_s 36 }

(the Integer#to_s method converts a number to a string representing it in a desired numeral system)

You can also do it this way:

'a'.upto('z').to_a + 0.upto(9).to_a
myarr = [*?a..?z]       #generates an array of strings for each letter a to z
myarr = [*?a..?z] + [*?0..?9] # array of strings a-z and 0-9

You can just do this:

("0".."Z").map { |i| i }

Try this:

alphabet_array = [*'a'..'z', *'A'..'Z', *'0'..'9']

Or as string:

alphabet_string = alphabet_array.join
letters = *('a'..'z')

=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]