Let's say I have an array of random numbers in no particular order. Let's say these are the ID #'s for people who ran in a marathon, and they're added to the array in the order they finish, something like:
race1 = [8, 102, 67, 58, 91, 16, 27]
race2 = [51, 31, 7, 15, 99, 58, 22]
This is a simplified and somewhat contrived example, but I think it conveys the basic idea.
Now a couple questions:
First, how could I get the IDs that are before and after a particular entry? Let's say I am looking at runner 58 and I want to know who finished before and after him.
race1, runner58: previous finisher=67, next finisher=91
race2, runner58: previous finisher=99, next finisher=22
Second, if I'm looking at the person who finished first or last, how can I have the "next" or "previous" loop back around the array?
race1, runner8: previous finisher=27, next finisher=102
race2, runner22: previous finisher=58, next finisher=51
Lastly, I'd like to show what position each runner finished in. Given just the array and a value in it, how can I find out what 'ordinal' position it is in the array? Ie:
race1: runner8=1st, runner102=2nd, runner67=3rd ... runner27=last
Thanks very much!
First & Second:
index = race1.find_index(58)
if !index.nil?
puts "#{race1[index-1], #{race1[index+1] || race1[0]}"
end
Lastly:
gem install linguistics
then
require 'linguistics'
Linguistics::use( :en )
race1.each_with_index {|runner, i| puts "runner#{runner}=#{(i+1).en.ordinal}"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With