Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: next / previous values in array, loop array, array position

Tags:

arrays

ruby

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!

like image 206
Andrew Avatar asked Mar 28 '11 19:03

Andrew


1 Answers

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}"}
like image 63
Jonas Elfström Avatar answered Sep 28 '22 01:09

Jonas Elfström