Home > Enterprise >  Variable does not equal variable when it should in ruby
Variable does not equal variable when it should in ruby

Time:01-26

I am making my first web server, but When i use the if statement to compare user input from html file with a string, they just skip it even if it is true.

require 'socket'
require 'pry'

class Parser

  def parse(req, clients)

    save = File.new("requests.txt", "w ")
    save.write(req.chomp)
    save.close
    words = IO.readlines("requests.txt").last(1)
    if words == "Username=test&Password=1234"
      success(clients)
    end
    #binding.pry

    puts words

  end
end

def success(succ_client)

  success_file = File.read("templates/success.html")
  stuff = "HTTP/1.1 200\r\n"   success_file.force_encoding('UTF-8')
  succ_client.puts(stuff)

end

def response(cli)

  file = File.read("templates/passpage.html")
  content = "HTTP/1.1 200\r\n"   file.force_encoding('UTF-8')
  cli.puts(content)

end

serv_sock = TCPServer.new('10.0.2.15', 8080)

loop {
  client = serv_sock.accept()
  requests = Parser.new
  requests.parse(client.readpartial(2043), client)
  response(client)

  client.close
  puts "Connected"
}

I tried using #compact!, nil?, and using pry to decode to find whats the issue, but I just cant find the problem, when i puts the words variable it puts the correct value but its just not the right one I guess. I tried decoding the words but that still didn't work unless i did it wrong. It has been 5 days on this problem and this is my first ruby program, and web-server, So ill appreciate any help I can get with this to move forward in life.

CodePudding user response:

There are several issues with your code.

Primarily, your call to IO.readlines("requests.txt").last(1) returns an Array of zero or one strings. However, you are comparing it to a single string. Since the string is not equal to the array, the comparison fails.

Likely, you want to use IO.readlines("requests.txt").last instead. This returns the last element or the array or nil if the array returned by the readlines method is empty.

Please have a look at the documentation of the Array#last method to learn more about the returned types of this method.

In addition to that, even if your if statement eventually matches, your intended call to the success method fill fail, because you have defined it in the global main object, rather than your Parser class.

Also, when you eventually call success from your parse method, you will be returning two responses as you also call the response method later. You may want to rethink the way you select the correct responses...

  • Related