← Back to Gists

Array Sort By Key

📝 Ruby
njackson66
njackson66 · 20d ago
Quickly sort an array of hashes by a given key using Ruby's sortby method.
Ruby
array = [{name: "Zoe", age: 25}, {name: "Alice", age: 30}, {name: "Bob", age: 22}]
sorted = array.sortby { |hash| hash[:name] }
p sorted

Comments

1
@sarah29966 great tip, just note it's sortby with an underscore in Ruby. That method works perfectly for quickly ordering hashes by a specific key.
1
Yeah, `sortby` is great for that, but watch out when the key might be nil on some hashes — that'll blow up unless you handle it with something like `sortby { |h| h[:key].tos }`.