Skip to content

Instantly share code, notes, and snippets.

@jrunning
Last active August 29, 2015 14:03
Show Gist options
  • Save jrunning/7d3aec317ee47691731f to your computer and use it in GitHub Desktop.
Save jrunning/7d3aec317ee47691731f to your computer and use it in GitHub Desktop.

Cary's version:

def doit(arr, *vals_at)
  arr.each_slice(2)
     .map {|s1,s2|
       [s1.split.last.to_i,[s1.tr(' ','').to_sym, s2.scan(/\d+/).map(&:to_i)]]}
     .to_h
     .values_at(*vals_at)
     .to_h
end

Alternative 1:

Wherein we assume OP only wants to transform all of the original data and not select a subset of it.

# Usage: doit1(arr)
def doit1(arr)
  arr.each_slice(2)
    .map {|s1, s2|
      [ s1.tr(' ', '').to_sym, s2.scan(/\d+/).map(&:to_i) ]
    }
    .to_h
end

Alternative 2:

Wherein we assume OP wants to select a subset of the data using symbol keys, e.g. :advert0.

# Usage: doit2(arr, :advert0, :advert4)
def doit2(arr, *vals_at)
  arr.each_slice(2)
    .map {|s1, s2|
      [ s1.tr(' ', '').to_sym, s2.scan(/\d+/).map(&:to_i) ]
    }
    .select {|k,_| vals_at.include?(k) }
    .to_h
end

Alternative 3:

Wherein we assume OP wants to select a subset of data using integer values.

# Usage: doit3(arr, 0, 4)
def doit3(arr, *vals_at)
  arr.each_slice(2)
    .map {|s1, s2|
      [ s1.tr(' ', '').to_sym, s2.scan(/\d+/).map(&:to_i) ]
    }
    .select {|k,_| vals_at.include? k[/\d+$/].to_i }
    .to_h
end

Alternative 4:

Wherein we do select before map to avoid processing values we're just going to discard.

# Usage: doit4(arr, 0, 4)
def doit4(arr, *vals_at)
  match_key = /\D(#{ vals_at.join(?|) })$/
  arr.lazy.each_slice(2)
    .select {|k,_| k =~ match_key }
    .map {|s1, s2|
      [ s1.tr(' ', '').to_sym, s2.scan(/\d+/).map(&:to_i) ]
    }
    .to_h
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment