Home > Back-end >  running ruby on terminal gives me a different output than leetcode
running ruby on terminal gives me a different output than leetcode

Time:12-09

I'm practicing leetcode and checking other people's solutions for the same exercise on my terminal gives a totally different output than expected. If I run it on leetcode it says the answer is correct... What might be causing this?

reversing the array of chars - ["h","e","l","l","o"] - like so:

def reverse_string(s)
   len = s.length
  (0...len/2).each { |i|
      temp = s[i]
      swap_index = len-i-1
      s[i] = s[swap_index]
      s[swap_index] = temp
  }
end

p reverse_string([["h","e","l","l","o"]])

output in my terminal -- 0...2

output in leetcode is as expected - ["o","l","l","e","h"]

Why does this happen?

thanks

CodePudding user response:

Ruby's p function will print the value you pass to it.

The value you are choosing to pass to it is the return value of reverse_string.

You should add a line to the end of reverse_string that specifies what you want to return from it. In this case the line can simply consist of s. You don't even need an explict return in this case.

  •  Tags:  
  • ruby
  • Related