Question

Forgive my lack of code but I can't quite figure out the best way to achieve the following:

two strings (stored as strings because of the leading 0 - they are phone numbers) :

a = '0123456700'
b = '0123456750'

I am trying to find a way to write them as a range as follows

0123456700 - 750

rather than

0123456700 - 0123456750

which I currently have.

It's not as straightforward as getting the last 3 digits of b since the range can vary and perhaps go up to 4 digits so I'm trying to find the best way of being able to do this.

Was it helpful?

Solution 2

Here's a method that returns the range:

def my_range(a, b)
  a = a.delete(" ") # remove all spaces from string                                                                                            
  b = b.delete(" ")
  a, b = b, a if a.to_i > b.to_i # a is always smaller than b                                                                                  
  ai, bi = a.to_i, b.to_i
  pow = 1
  while ai > 1
    pow += 1
    len = pow if ai % 10 != bi % 10
    ai /= 10
    bi /= 10
  end
  a + " - " + b[-len..-1]
end

puts my_range("0123456700", "0123456750")   # 0123456700 - 750
puts my_range("0123456669", "0123456675")   # 0123456669 - 675
puts my_range("0123400200", "0123500200")   # 0123400200 - 3500200
puts my_range("012 345 678", "01 235 0521") # 012345678 - 350521

OTHER TIPS

I'd look up the index of the first unequal pair of characters:

a = '0123456700'
b = '0123456750'

index = a.chars.zip(b.chars).index { |x, y| x != y }
#=> 8

And extract the suffix with:

"#{a} - #{b[index..-1]}" if index
#=> "0123456700 - 50"

From my personal library (simplified):

def common_prefix first, second
  i = 0
  loop{break unless first[i] and second[i] == first[i]; i += 1}
  first[0, i]
end

a = "0123456700"
b = "0123456750"
c = "0123457750"

common_prefix(a, b)
# => "01234567"

"#{a} - #{b.sub(common_prefix(a, b), "")}"
# => "0123456700 - 50"

"#{a} - #{c.sub(common_prefix(a, c), "")}"
# => "0123456700 - 7750"

Note. This will work correctly only under the assumption that all strings are right padded with 0 to be the same length.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top