0

What is the syntax for sorting an array alphabetically by the key of a hash or by a string? I would like to sort the following:

['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']

to give the following:

['apple', 'bob', {'lasagne' => 'munch'}, 'sandwich', 'tangoed']
0

2 Answers 2

2

Not clear what to do when a hash includes more than one key. Considering always the first key in a hash:

['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']
.sort_by{|e| [*e].flatten.first}
#=> ["apple", "bob", {"lasagne"=>"munch"}, "sandwich", "tangoed"]
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Sawa thanks for your answer, could you tell me what the [*e] part does before the flatten?
If to_a is defined (which is the case for hashes), then it applies to_a to it, remove the [] surrounding it, and surrounds it with another []. Otherwise (which is the case for strings), it surrounds it with [].
0

You can just translate your words into symbols:

arr = ['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']

arr.sort_by { |e| e.is_a?(String) ? e : e.keys.first }
  #=> ["apple", "bob", {"lasagne"=>"munch"}, "sandwich", "tangoed"]

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.