0

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?

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145

1 Answers1

2

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"]
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • Thank you. I notice you didn't have to use a regular expression to split up the string into words. Does the automatic splitting only occur for regular spaces or will it also occur for other types of spaces (like non-breaking spaces)? –  Feb 12 '17 at 20:50
  • @Natalia check out [String#`split`](https://ruby-doc.org/core-2.2.0/String.html#method-i-split) for being sure what to use. regex is ok if you know you'll get something more complicated that just a spaced string. You could change in my example to `.map { |string| string.split(/\s+/) }` – Andrey Deineko Feb 12 '17 at 20:52
  • Thanks. Also I noticed this clause "|ar| join(' ')" should probably be "|ar| ar.join(' ')" –  Feb 12 '17 at 21:09