Home > Enterprise >  ruby split 2 chars from an array of 4 chars
ruby split 2 chars from an array of 4 chars

Time:11-18

i have an 4 characters array = ["0222"] Need to split in 2 groups of 2 each

Need to get array = ["02","22"] Try split, but can´t get the result i need.

CodePudding user response:

You could try doing a regex match all on the pattern \d{1,2}:

nums = "0222".scan(/\d{1,2}/)
puts nums

This prints:

02
22

CodePudding user response:

Maybe you could use each_slice:

irb> array = ["0222"]
=> ["0222"]
irb> array[0].chars.each_slice(2).map(&:join)
=> ["02", "22"]
  • Related