I’m trying to reverse words in an array of string variables, but split doesn’t seem to be working.
Testing in IRB I get “NoMethodError: private method `split’ called for Array”, which I’m assuming has something to do with my program quietly doing nothing.
For example, I have:
nameList = ["Joe Blow", "Mary Sue", "Alice Mallory"].
I expect to return:
["Blow Joe", "Sue Mary", "Mallory Alice"].
So I iterate through the array, splitting, reversing and joining. This is where nothing happens:
nameList.each { |x|
x.to_s.split(' ').reverse!.join(' ')
puts x #testing here
}
This outputs:
Joe Blow
Mary Sue
Alice Mallory
I must be missing something extremely simple, as this can’t be too difficult.
You’re splitting, reversing and discarding the result. Check this out.
If you want to apply some transformation to every element of array, get new value and construct a new array of these values, it is idiomatic to use
Array#mapfunction.Also, here you shouldn’t use bang version of reverse (
reverse!). It has destructive semantics.reversecreates a new reversed array, whilereverse!updates source array in place. In this case source array is a temp variable, so it makes no difference result-wise. But I consider it confusing and distracting.