0

I'm just trying to sort my strings alphabetically but while maintaining their position inside an array. For example, I have :

myArray = ["tree", "house", "show", "merit", "timer"]

and I'd like to perform an each loop on it in order to output :

myArray = ["eert", "ehosu", "hosw", and so on...]

I wanted to do something like this :

myArray.each do |x|
    x.chars.sort.join
end

For a single string that works but I guess "chars" doesn't work for multiple strings in an array. Or maybe it does and I'm not doing it right. Basically how would I modify it in order to get that output?

1
  • You are not sorting the strings, you are sorting the letters in a string. Commented Oct 31, 2014 at 4:43

2 Answers 2

2

All you need in order to make this work is to call map on myArray, instead of each.

The map method will change each element to the result of running the block on the original element.

myArray = ["tree", "house", "show", "merit", "timer"]
myArray.map do |x|
  x.chars.sort.join
end
# => ["eert", "ehosu", "hosw", "eimrt", "eimrt"]

Another thing to mention is that you are using camelCase for your variables, while the convention in Ruby is snake_case (my_array would be preferable).

Sign up to request clarification or add additional context in comments.

1 Comment

Very true. Thanks a lot! I knew it wouldn't be too complicated.
0

You are sorting each element in the array. To do this, call the map function. I then broke down each element into multiple smaller array elements, and sorted that array. I transformed that array back into a sentence by using the join method.

myArray.map{|x|x.chars.sort{|x,y|x<=>y}.join}

=> ["eert", "ehosu", "hosw", "eimrt", "eimrt"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.