AltBrian
AltBrian

Reputation: 2572

Sort an array of words by the last letter

I am trying to sort an array of words by their last character.

def array_sort_by_last_letter_of_word(array)
  list = array[-1,1]
  list.sort { |a,b| b <=> a }
end

puts array_sort_by_last_letter_of_word ['sky', 'puma', 'maker']

The output I get is just "maker".

Upvotes: 3

Views: 2576

Answers (2)

Max
Max

Reputation: 22385

Andrey's answer is definitely the way to do this. But to understand what's going wrong with your code:

list = array[-1,1]

This syntax is for getting a subarray of an array. The pattern is array[start, length] to get an array starting at index start with length length. So you are asking for an array starting at -1 (which means the last index) of length 1 i.e. just the last element of the array. So last = ['maker']. That's why your sort method is just returning that element.

You want to get the last character inside the sort block, which is what determines how strings are compared

array.sort { |a,b| a[-1] <=> b[-1] }

Also note that a needs to be left of b, otherwise the array is sorted in reverse.

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52377

def array_sort_by_last_letter_of_word(array)
  array.sort_by { |word| word[-1] }
end

Rails version (using String#last):

def array_sort_by_last_letter_of_word(array)
  array.sort_by(&:last)
end

Upvotes: 6

Related Questions