Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Simple Symbols Ruby
    My code seems to work fine in IRB (ruby 2.0.0p247), but I'm getting different results when I submit my answer for this problem. Often times, I'll get nil or 0. What's wrong with my code?
    def SimpleSymbols(str)
      abc = ('a'..'z').to_a
      0.upto(str.length - 1) do |i|
        if (abc.include? str[0]) || (abc.include? str[(str.length - 1)])
          @answer = 'false'
          if abc.include? str[i]
            @answer = check_neighbors(str[i], str)
      return @answer
    def check_neighbors(char, string)
      string = string.split(//)
      if (string[string.find_index(char) - 1] == '+') && (string[string.find_index(char) + 1] == '+')
        return 'true'
        return 'false'
    hellricko asked this question on 6/30/15 | ruby, symbols
  • +
  • 0
  • -
  • I tried running your code and I can see a couple of design problems. (1) The way you are checking for characters. I believe that find_index(char) will find the first instance of the character in the string. You might do better by passing the index as a parameter instead of the character. So if you run this code on "++q+qqqqqq+" your function is going to return true because it gets passed "q" as the character to check, and just checks the first instance, which isn't a problem because it has +s on both sides. (2) Your @answer variable winds up getting overwritten every time the loop executes. So this input: "++a+bbbb+c+" will return true, because even though @answer winds up being set to false when it checks "b," that gets overwritten to true when searching for c. Also, it's good that you're checking the first and last places within the string, but you probably should pull that out of the loop or rework it. I can see a way to do this problem where it does make sense to do that check every time the loop iterates, but it doesn't look like you're taking that approach. Also, it's weird to be using "@answers" as a variable name because I think in Ruby the @ symbol denotes an instance variable in a class. This is also a good chance to learn some things about regular expressions. Doing this check: if /[a-z]/ =~ str[i] is a more standard way of checking to see if something is a (lower case) letter than creating an array of characters and seeing if the array includes your test character. There are probably even better ways of checking using regular expressions. Good luck. You are certainly on the right track.
    Login to write an answer