Wednesday, August 21, 2013

Coderbyte: AB Check (Ruby)

PROBLEM

Have the function ABCheck(str) take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in true because there is exactly three characters between a and b). Otherwise return the string false.

SOLUTION

def ABCheck(str)
    str_letter = str.split('')
    str_letter.each_with_index { |placeholder, index| return true if str_letter[index] == "a" and str_letter[index+4] == "b" }
    str_letter.each_with_index { |placeholder, index| return true if str_letter[index] == "b" and str_letter[index+4] == "a" }
    return false
end
  
print ABCheck(STDIN.gets)