Ruby: next / previous values ​​in an array, an array of loops, an array position

Let's say I have an array of random numbers in a specific order. Let's say this is ID # for people who ran in a marathon, and they are added to the array in the order in which they end, for example:

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 few questions:

First, how can I get the identifiers that are before and after a certain record? Let's say I'm 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

Secondly, if I look at the person who finished the first or last, how can I get the “next” or “previous” loop around the array?

race1, runner8: previous finisher=27, next finisher=102
race2, runner22: previous finisher=58, next finisher=51

, , . , , "" ? :

race1: runner8=1st, runner102=2nd, runner67=3rd ... runner27=last

!

+5
5

:

index = race1.find_index(58)
if !index.nil?
  puts "#{race1[index-1], #{race1[index+1] || race1[0]}"
end

:

require 'linguistics'
Linguistics::use( :en )
race1.each_with_index {|runner, i| puts "runner#{runner}=#{(i+1).en.ordinal}"}
+7

# 1 # 2 , id, , :

class Array
  def prev_next(id)
    idx = self.index(id)
    raise Error.new("no racer with id #{id}") unless idx
    [self[idx-1], self[(idx+1)%self.size]]
  end
end
race1.prev_next(58) # => [67, 91]
race1.prev_next(8) # => [27, 102]

, -1 Ruby array.slice , . :

class Integer
  def ordinalize
    s = self.to_s
    case s
      when /1[123]$/ then s + 'th'
      when /1$/ then s + 'st'
      when /2$/ then s + 'nd'
      when /3$/ then s + 'rd'
      else s + 'th'
    end
  end
end
race1.each_with_index {|x,i| puts "runner#{x}=#{(i+1).ordinalize}"}
# runner8=1st
# runner102=2nd
# runner67=3rd
# ...
+5

find_index, , .

runner_index = race.find_index finisher_number #find the index of the racer
previous_runner = race[runner_index - 1] #a negative index will wrap around
next_runner = race[runner_index + 1] || race[0] #use a null guard to wrap to the front
+2

, , , ruby ​​1.9, rotate, ruby ​​1.8.7, - index

race1[race1.index(58) +1] will give 98 (the next one)
race1[race1.index(58) -1] will give 67 (the previous one)

( 0)

0

:

race1.rotate(race1.index(58) + 1).first # next
race1.rotate(race1.index(58) - 1).first # previous

: : http://jamonholmgren.com/rubymotion-react-pattern/

0

All Articles