Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first differing character between two Strings in Ruby

Tags:

string

ruby

I have two strings.

str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"

I want to find the first index at which the two strings differ (i.e. str_a[i] != str_b[i]).

I know I could solve this with something like the following:

def diff_char_index(str_a, str_b)
  arr_a, arr_b = str_a.split(""), str_b.split("")
  return -1 unless valid_string?(str_a) && valid_string?(str_b)
  arr_a.each_index do |i|
    return i unless arr_a[i] == arr_b[i]
  end
end

def valid_string?(str)
  return false unless str.is_a?(String)
  return false unless str.size > 0
  true
end

diff_char_index(str_a, str_b) # => 10

Is there a better way to do this?

like image 896
etdev Avatar asked Aug 30 '25 18:08

etdev


2 Answers

Something like this ought to work:

str_a.each_char.with_index
  .find_index {|char, idx| char != str_b[idx] } || str_a.size

Edit: It works: http://ideone.com/Ttwu1x
Edit 2: My original code returned nil if str_a was shorter than str_b. I've updated it to work correctly (it will return str_a.size, so if e.g. the last index in str_a is 3, it will return 4).

Here's another method that may strike some as slightly simpler:

(0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size

http://ideone.com/275cEU

like image 120
Jordan Running Avatar answered Sep 02 '25 06:09

Jordan Running


i = 0
i += 1 while str_a[i] and str_a[i] == str_b[i]
i
like image 25
sawa Avatar answered Sep 02 '25 08:09

sawa