0

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 :)

1
  • Do you just want to know, whether a certain key already exists in the Hash, or whether a certain key exists and has a certain value. In general, you want the former (the latter does not make much sense in your context), but taken your question literally, you meant the latter. Commented Jun 20, 2022 at 14:08

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

@passwords.has_key?(service) is an alias.
0

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 

1 Comment

The first version would fail, if you have a Hash which does have an entry for service, but that entry is nil, and password is nil as well; or, more general, if password happens to be that value which the Hash is configured to return for a missing key.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.