How to reverse every other word in the string

reverse_alternate("I am super happy today")
#return "I ma super yppah today"
reverse_alternate("I love code.")
#return "I evol code."
temp_array = string.split{|word,index| index.odd? ? word.reverse : word }.join(" ")
def reverse_alternate(string)
temp_arr = string.split{|word,index|
index.odd? ? word.reverse : word }.join(" ")
  1. String instance method .reverse (.reverse reverses the)
  2. Integer instance method .odd? (.odd? returns true if an integer is odd, return false if it’s even.)
  3. Array instance method .join (.join transform an array into a string.)
  4. .map.with_index(|item, index|) This chained enumerable helps us to manipulate index, item and collect them back as a new array.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introducing DODO’s Updated Roadmap (Q4 2021 to 2022)

How to install SSL certificate for Nginx server in Amazon Linux

Designing for the Platform — API design

How to Deploy Private GitHub Repositories to cPanel With GitHub Actions [Continuous Deployment…

How To Move Data Between Azure VM and Azure Blob Storage

Redesigning Ellipsis Digital’s Website is Crucial To Our Growth Process

Distributed and Cloud Computing

Why you should learn Flutter?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chenyun Zhang

Chenyun Zhang

More from Medium

Smart Ways to Work Around Children

Horus Heresy Book Report 1: Garviel and Friends

Cover of Horus Rising, depicting legion of armored soldiers assaulting a city

Weight loss after 45; easy tips for staying healthy

How to Use GoodRX to Hack Prescription Costs