Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby- sort array based on string in index

I've been staring at sort forums forever now and I officially accept that i do not understand whats going on.

I have an array called "people" with multiple index's each array index looks like this

("Steven", "32", "Detroit", "single")

("Fred", "19", "Boston", "married")

("Jason", "25", "san_fransisco" "single")

I want to sort these index's by city (3rd entry of an index)

I've looked at so many different websites and i'm not following this at all. Can someone help me out with an answer and briefly explain whats going on? Is this even possible using an array?

Thanks!

like image 644
Jaron Bradley Avatar asked Apr 20 '26 14:04

Jaron Bradley


1 Answers

people = [
  ["Steven", "32", "Detroit", "single"],
  ["Fred", "19", "Boston", "married"],
  ["Jason", "25", "san_fransisco", "single"],
]

people.sort_by{|p| p[2]}
like image 128
sawa Avatar answered Apr 22 '26 03:04

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!