Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string each two characters with Ruby

I want to reverse a string each two characters with Ruby.

The input:

"0123456789abcdef"

The output that I expect:

"efcdab8967452301"
like image 695
Arturo Herrero Avatar asked Apr 02 '26 06:04

Arturo Herrero


2 Answers

I'm not sure if this is the best way to do it:

"0123456789abcdef".scan(/../).reverse.join == "efcdab8967452301"
like image 80
Arturo Herrero Avatar answered Apr 03 '26 19:04

Arturo Herrero


"0123456789abcdef".gsub(/../, &:reverse).reverse
# => "efcdab8967452301"
like image 39
sawa Avatar answered Apr 03 '26 21:04

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!