Ruby regex for a split every four characters not working
I'm trying to split a sizeable string every four characters. This is how I'm trying to do it:
big_string.split(/..../)
This is yielding a nil array. As far开发者_运维百科 as I can see, this should be working. It even does when I plug it into an online ruby regex test.
Try scan
instead:
$ irb
>> "abcd1234beefcake".scan(/..../)
=> ["abcd", "1234", "beef", "cake"]
or
>> "abcd1234beefcake".scan(/.{4}/)
=> ["abcd", "1234", "beef", "cake"]
If the number of characters isn't divisible by 4, you can also grab the remaining characters:
>> "abcd1234beefcakexyz".scan(/.{1,4}/)
=> ["abcd", "1234", "beef", "cake", "xyz"]
(The {1,4}
will greedily grab between 1 and 4 characters)
Hmm, I don't know what Rubular is doing there and why - but
big_string.split(/..../)
does translate into
split the string at every 4-character-sequence
which should correctly result into something like
["", "", "", "abc"]
Whoops.
str = 'asdfasdfasdf'
c = 0
out = []
inum = 4
(str.length / inum).round.times do |s|
out.push(str[c, round(s * inum)])
c += inum
end
精彩评论