3.14thon
3.14thon

Reputation: 27

While loop not looping - Ruby

When str[0] is "a" and str[4] is "b" I get true. However, when "a" is in another position and is separated by three spaces from "b" I get false.

Any help would be great!

def ABCheck(str)

  str.downcase.split()
  x = 0
  while x < str.length - 4
    return true if ((str[x] == "a") && (str[x + 4] =="b"))
      x += 1
    return false

  end     
end

puts ABCheck("azzzb")
#Currently puts "true"
puts ABCheck("bzzabzcb")
#Currently puts "false" - even though it should print true

Upvotes: 0

Views: 70

Answers (2)

locoboy
locoboy

Reputation: 38910

You're calling false before your while loops is complete. You need to call it after the while loop.

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122373

That's because return false is called before you expected. It should be put outside the loop:

def ABCheck(str)
  str.downcase.split()
  x = 0
  while x < str.length - 4
    return true if ((str[x] == "a") && (str[x + 4] =="b"))
    x += 1
  end  
  return false   
end

Upvotes: 4

Related Questions