Raymond Ruiz-Veve Raymond Ruiz-Veve - 11 months ago 46
Ruby Question

Create an Array from another Array

I have an array that looks like this:

Array_1 = ["A1", "A2", "A3", "A4", "A5", "B1", "B2", "B3", ..., "Z5"]

I want to create another array with the elements of
that come after

Array_2 = ["B1", "B2", "B3", ..., "Z5"]

I have an ugly way that subtracts two arrays to create a third array, but I feel like there is bound to be a classy ruby way of doing something that should be simple. Any help would be amazeballs.

Array_1 = ["A1", "A2", "A3", "A4", "A5", "B1", "B2", "B3", "Z5"]

  # => ["B1", "B2", "B3", "Z5"] 

(I suppose we should first compute idx = Array_1.index("A5") to make sure it's non-nil.)

. . .

Another way makes use of Ruby's little-used flip-flop operator:

Array_1.select { |e| e=="A5" .. false ? true : false }[1..-1]
  #=> ["B1", "B2", "B3", "Z5"]

The expression remains false until e=="A5" is true, and remains true until the expression following the two dots is true. Therefore,

Array_1.select { |e| e=="A5" .. false ? true : false }
  #=> ["A5", "B1", "B2", "B3", "Z5"]

[1..-1] is tacked on to return this array without "A5".

The flip-flop operator must be part of a conditional expression, which is why we cannot write:

Array_1.select { |e| e=="A5" .. false }[1..-1]
  #ArgumentError: bad value for range

(for e=="A5" .. false is treated as a normal range).