Home > other >  Ruby - Checking a hash key/value pair doesn't already exist before adding to a hash
Ruby - Checking a hash key/value pair doesn't already exist before adding to a hash

Time:06-21

Ruby newbie here! I have a beginners challenge for a very basic password manager that I've had a complete mind blank trying to solve. One of the methods that needs to be defined is that it can ensure all service names and passwords are unique.

Snippet below is where the first version from a previous challenge left off which I THINK will help as a foundation to build on (I've added a comment line where I think the additional pieces will go from there).


  def initialize
    @passwords = {}
  end

  def add(service, password)
    #something here to check hash before adding to @passwords hash?????
    return @passwords[service] = password
    end
  end

  def services
    @passwords.keys 
  end

end

Any pointers greatly appreciated! Do let me know if any further context is needed etc. First time reaching out in here so still getting used to it all!

Thanks folks :)

CodePudding user response:

I would do this:

def add(service, password)
  if @passwords.key?(service)
    puts "Error: A password for #{service} does already exist."
  else
    @passwords[service] = password
  end
end

CodePudding user response:

You can just check if @passwords[service] == password and password is not nil to avoid the case when @passwords[service] is nil and password is nil so that not to have nil == nil comparison as user1934428 mentioned in comments section.

def add(service, password)
  return if @passwords[service] == password && password
  @passwords[service] = password
end

Or more tricky

@passwords.to_a.include?([service, password])
def add(service, password)
  return if @passwords.to_a.include?([service, password])
  @passwords[service] = password
end

Or monkey patch Hash class

class Hash
  def has_pair?(key, value)
    key?(key) && self[key] == value
  end
end
def add(service, password)
  return if @passwords.has_pair?(service, password)
  @passwords[service] = password
end
  • Related