user7055375
user7055375

Reputation:

How do I switch the positions of words within a string?

I have an array of strings, each with at least one space in them. I would like to tkae the last part of the string and put it at the beginning, for every element in the array. So for example if I have this in my array

["RUBY RAILS"]

I would like the result to be

["RAILS RUBY"]

I tried this

data.map! {|str| "#{str.split(/\s+/).last} #{str.split(/\s+/).first}" }

but the only problem is that if the string has more than two words the above doesn't work. If a string has more than two words, like

["ONE TWO THREE"]

I would want the reuslt to be

["THREE ONE TWO"]

but my above function doesn't do that. How can I change my function so that it will do this?

Upvotes: 0

Views: 122

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

You're looking for Array#rotate:

["ONE TWO THREE"]
  .map(&:split)               #=> [["ONE", "TWO", "THREE"]]
  .map { |ar| ar.rotate(-1) } #=> [["THREE", "ONE", "TWO"]]
  .map { |ar| ar.join(' ') }     #=> ["THREE ONE TWO"]

Upvotes: 2

Related Questions