user4462666
user4462666

Reputation:

How do Slice a string into pairs

For the project I am doing, I need to make pairs out of the input, but I can't figure out how, I could use some help.
How it is:

2209222717080109

How I want it to become:

["22","09","22","27","17","08","01","09"]

Upvotes: 1

Views: 879

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

"2209222717080109".scan /../
  #=> ["22", "09", "22", "27", "17", "08", "01", "09"] 

Upvotes: 4

Ajedi32
Ajedi32

Reputation: 48428

Convert it to a string, convert that into an array of characters, then take each consecutive slice of two characters, and join each of those slices together:

2209222717080109.to_s.chars.each_slice(2).map(&:join)
#=> ["22", "09", "22", "27", "17", "08", "01", "09"]

Upvotes: 2

Tonmoy
Tonmoy

Reputation: 174

input = "2209222717080109"
input.chars.each_slice(2).map(&:join)
["22", "09", "22", "27", "17", "08", "01", "09"]

Upvotes: 3

Related Questions