Function does not modify variable value

Asked

Viewed 32 times

0

I’m trying to make an App that modifies a DB Redis, but when I send the function connect to a user he should do Conectado = true and UsuarioConectado = UsuarioQueConectou.

But when the function Desconectar(DB, connected, usernameConnected) checks whether connected == true he should ask if I want to disconnect.

What if connected == false (standard) it says it is already disconnected, but when connected it does Conectado == true, but he did not modify.

And if I use $connectado it gives error because it does not allow to use global variables.


My code:

connected = false
connectedUser = "none"

def connectUser(db, conectado, usrconnected)
    puts "What's The Username"
    getusername = gets.chomp
    puts "What's The Password"
    getpassword = gets.chomp

    achou = false
    achou2 = false
    ...

    def disconectUser(connected, usercnt)

    if connected and usercnt != "" and !(isNul(usercnt))
      puts "Disconect ? (Y , N)"
      tmp2 = gets.chomp
      if tmp2 == "Y" or tmp2 == "y"
        connected = false
        usercnt = "none"
      elsif tmp2 == "N" or tmp2 == "n"
        puts "Ok ! Canceled With Sucess !"
      else
        puts "Unknown #{tmp2} -> Y or N !"
      end
    elsif !connected
      puts "Already Disconnected !"
    else
      puts "Error With Var's ! (Connected : Boolean)"
    end
  end

In Case You Need To Test:

  • Open Redis-server.exe for First
  • Open App.Rb (Open with CMD If An Error Appears And you might want to see)

Downloads:

1 answer

1


Classic problem of "parameters by reference or value".

In ruby the function parameters are passed by reference, but when you do an assignment on that variable ruby creates a new variable with another address in memory. Example:

def change_value arg
  puts "#{arg} - #{arg.object_id}" # true - 3
  arg = false # a função = cria outra variável
  puts "#{arg} - #{arg.object_id}" # false - 5
end

connected = true
puts "#{connected} - #{connected.object_id}" # true - 3
change_value connected
puts "#{connected} - #{connected.object_id}" # true - 3

One solution would be to store this Connected and usrcnt information in the redis itself or to have a class that stores this information in an object and manipulates the state of that object. Example:

class User
  attr_accessor :name, :connected

  def initialize name, connected
    @name = name
    @connected = connected
  end

  def connected?
    !!@connected
  end
end

user = User.new 'Joao', false

def connect user
  # .....
  user.connected = true
end

def disconnect user
  # .....
  user.connected = false
end

puts "Inicial: #{user.connected?}" # false
connect user
puts "Conectado: #{user.connected?}" # true
disconnect user
puts "Desconectado: #{user.connected?}" # false

Browser other questions tagged

You are not signed in. Login or sign up in order to post.