Search code examples
rubycloud9-ide

Code doesn't work in coderbytes but it works in Cloud9


In Cloud9 I use the following code and it works.

def LongestWord(sen)
  i = 0
  cha ="&@%*^$!~(){}|?<>"
  new = ""
  while i < sen.length
    i2 = 0
    ch = false
    while i2 < cha.length
      if sen[i] == cha[i2]
        ch = true
      end
      i2 += 1
    end

    if ch == false
      new += sen[i].to_s
    end
    i += 1
  end

  words = new.split(" ")
  longest = ""
  idx = 0
  count = 0
  while idx < words.length
    word = words[idx]

    if word.length > count
      longest = word
      count = word.length
    end
    idx += 1
  end   
  # code goes here
  return longest

end

# keep this function call here 
# to see how to enter arguments in Ruby scroll down   
LongestWord("beautifull word") 

In Codebytes in the exercise "Longest Word" you have to use the same STDIN in the arguments. It is the same code but changing the argument but it doesn't work:

def LongestWord(sen)
  i = 0
  cha ="&@%*^$!~(){}|?<>"
  new = ""
  while i < sen.length
    i2 = 0
    ch = false
    while i2 < cha.length
      if sen[i] == cha[i2]
        ch = true
      end
      i2 += 1
    end

    if ch == false
      new += sen[i].to_s
    end
    i += 1
  end

  words = new.split(" ")
  longest = ""
  idx = 0
  count = 0
  while idx < words.length
    word = words[idx]

    if word.length > count
      longest = word
      count = word.length
    end
    idx += 1
  end   
  # code goes here
  return longest

end

# keep this function call here 
# to see how to enter arguments in Ruby scroll down   
LongestWord(STDIN.gets) 

I think may be something is creating some kind of conflict with the browser. The output shows a lot of numbers. Can some one help me testing the code?. Any feedback is appreciated, thanks!


Solution

  • Coderbyte is running your code on an old version of Ruby - Ruby 1.8.7

    In this version of Ruby, using an index into a string like sen[i] doesn't return the character at i, it returns the numeric ASCII value of that character instead. That's where the numbers are coming from.

    To get the code to work on Ruby 1.8.7 you can replace some_string[i] with some_string[i, 1] - this variation returns the substring of length 1 starting at i so is the same as the behaviour of some_string[i] in more recent Ruby versions. See the docs here for more details.