-3

a = '123712638126378123681273'

i have

=> a = ['12','37', ...... ]

I tried to use split but I do not know how to order it

help me

  • 3
    Not sure what you mean by "binary indexes", but based on your example output, you might be looking for `a.scan(/../)` – Stefan Oct 05 '21 at 08:04
  • 1
    Aside from the mysterious expression _binary indexes_, what do you mean by _order it_? For sorting arrays, you have the `sort` method. Please be a bit more precise when asking questions. – user1934428 Oct 05 '21 at 08:16
  • You might want to show the complete expected output (not just the first 2 elements). If it is too long to type, use a shorter example input. Also, include your code ("I tried to use split"), even if it is not working as expected. – Stefan Oct 05 '21 at 09:08

2 Answers2

2

I would do:

a.scan(/\d{2}/)
#=> ["12", "37", "12", "63", "81", "26", "37", "81", "23", "68", "12", "73"]
spickermann
  • 100,941
  • 9
  • 101
  • 131
0

Input

a = '123712638126378123681273'

Code

p a.gsub(/.{2}/).to_a

Or

p a.chars.each_slice(2).map(&:join)

Output

["12", "37", "12", "63", "81", "26", "37", "81", "23", "68", "12", "73"]
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
  • Can you explain the `gsub`-`reject` one? What are you substituting (are you?) and why the need to reject empty elements? – Stefan Oct 05 '21 at 08:59
  • @Stefan For some reason, when I execute this `a.gsub(/.{,2}/).to_a` it prints with empty space at the end. I don't know why, so I have included the reject. You could help me here as to why this code `a.gsub(/.{,2}/).to_a` includes the empty space. – Rajagopalan Oct 05 '21 at 09:30
  • `{,2}` is equivalent to `{0,2}`, i.e. it matches 0, 1, or 2 times. To only match two occurrences, use `{2}`. (and maybe prefer `scan` over `gsub` if you don't want to replace anything) – Stefan Oct 05 '21 at 10:01
  • @Stefan Oh that's exactly the problem, Now I have updated the answer. And regarding the `gsub`, spickermann has already used `scan` and I wanted to show another way so used `gsub`. – Rajagopalan Oct 05 '21 at 10:17