! - negate match
/ - start of regex
[aA] - Take first char if is aA char (the aA is in order to take both
down and upcase)
.{3} - take exact 3 any char after aA
[zZ] - take the 5th position if is zZ char (the zZ is in order to take
both down and upcase)
/ - end regex
while count < letters.length
current_letter = letters[count]
if current_letter != a
count += 1
next
end
next_index = count + 1
while next_index < count+4 && next_index < letters.length
if letters[next_index] == "z"
return true
end
next_index += 1
end
count += 1
end
return false
end
Fabio, I tried running yours and the first two tests fail.
Dansei…that’s a sweet solution!
def nearby_az(string,range=3)
string.each_char.each_with_index do |letter,i|
return true if letter==“a” && string[i+1,range].index(“z”)
end
false
end
What’s going on here exactly, you have two iterators running
side-by-side? One checks for letter to equal “a” and the other checks if
index within a range = “z” ?
Gives you an iterator over each character and your iteration looks like
this
a c c z g h
Next,
string.each_char.each_with_index
takes the previous iterator and returns a new iterator whose elements
are an array with the element and its index. It looks like this:
[a,0] [c,1] [c,2] [z,3] [g,4] [h,5]
Inside the loop, we check if the first character is an ‘a’ and if a ‘z’
is to be found within 3 characters. We need the current index for this.
/[aA].{2}[zZ]/.match(string)
This fails not because of the ‘2’, but because this check for exactly 2
characters after an ‘a’, and only then for a ‘z’.
It should be
/[aA].{0,2}[zZ]/.match(string)
This checks for 0 to 2 characters after an ‘a’. Note that it accepts
upper case letters as well: “Afgz”
The way I interpret “within 3 characters” is that “aggz” should match,
but “agggz” should not. So there may be at most 2 other characters after
an ‘a’?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.