3

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
user5664615
  • 400
  • 1
  • 10
  • 17
Dave
  • 313
  • 1
  • 3
  • 16
  • [Star](https://stackoverflow.com/a/918475/6611487) & [Question Mark](https://stackoverflow.com/a/1345854/6611487) in Ruby – boop_the_snoot Jul 31 '17 at 15:21
  • 1
    FYI: `[*?a..?z] + [*?0..?9]` can be combined into a single `[*?a..?z, *?0..?9]` – Stefan Jul 31 '17 at 15:39
  • Yes thanks Im not actually using this code I was just curious as to what was going on behind the scenes – Dave Jul 31 '17 at 15:44

1 Answers1

4

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> 
builder-7000
  • 7,131
  • 3
  • 19
  • 43
Simple Lime
  • 10,790
  • 2
  • 17
  • 32
  • 4
    More specifically, `*` expands the range into an argument list and `[...]` turns these arguments into an array. – Stefan Jul 31 '17 at 15:37
  • 1
    For completeness, I'll mention that these days it is typically done `*('a'..'z')` or `('a'..'z').to_a`. – Mark Thomas Jul 31 '17 at 17:37
  • @Mark,perhaps obvious, but I'll note that `*('a'..'z')` can only be used as an argument; for an assignment, `a = [*('a'..'z')]` or `a = ('a'..'z').to_a`. – Cary Swoveland Jul 31 '17 at 19:26