Dave
Dave

Reputation: 323

Don't understand a bit of code RUBY = [*?a..?z]

I found this code from a few years back. I understand what this code does but not how. Could anyone explain what the * and the ? are doing here? I haven't seen them used like this before.

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

Upvotes: 3

Views: 199

Answers (1)

Simple Lime
Simple Lime

Reputation: 11050

The ? is just a character literal syntax, it used to have special meaning in ruby < 1.9, but now ?a is just the same as doing "a"

Then .. is creating a Range and * just expands that into an argument list and the [ ] pair turn that into an array.

Wish my google-fu was enough to get some decent documentation links or explanations beyond that, but searching for these ones is extremely difficult.

Updated: ?a is actually the same as "a" not 'a' as mentioned earlier. To see this run (IRB tags left in to help illustrate what's happening):

irb(main):001:0> print ?\t
    => nil
irb(main):002:0> print "\t"
    => nil
irb(main):003:0> print '\t'
\t=> nil
irb(main):004:0> 

Upvotes: 4

Related Questions