Number mapper for Ruby


#1

The idea is to create two arrays that are one shift apart. We want to be able to compare values at same indices. Since this is from a number, we will naturally carry along its list representation.

def maps(num)
  n = num.to_s.split('').map { |i| i.to_i }
  m = n.length
  l = n[0, m-1]
  r = n[1, m]
  return l, r, n
end
k = maps(123456789)
print k[0].each { |i| i }
puts
print k[1].each { |i| i }
puts
print k[2].each { |i| i }
puts

Output

12345678
23456789
123456789

#2

The objective is to be able to compare adjacent values in one array by giving them identical indices in two separate arrays.


#3

I ended up tossing that approach and went with a single array.

def parity_match(num)
  n = maps(num)
  x = 1
  while x < n.length do
    if n[x-1] % 2 == 0 && n[x] % 2 == 0
      if n[x-1] != 0 && n[x] != 0
        n.insert(x,'*')
        x = x + 1
      end
    elsif n[x-1] % 2 != 0 && n[x] % 2 != 0
      n.insert(x,'-')
      x = x + 1
    end
    x = x + 1
  end
  n = n.join('')
  return n
end
def maps(num)
  num.to_s.split('').map { |i| i.to_i }
end

What is most embarrassing, or just plain newbie, is that regular expressions made this into a one liner and I just spent a day on this problem only to come up with a procedure.

def parity_match(num)
  num.to_s.gsub(/(?<=[13579])([13579])/, '-\1').gsub(/(?<=[2468])([2468])/, '*\1') 
end

There is a lesson in here somewhere...