2

Hello I need a bit of help.

Here is what I want to do.

  1. Check if hash already has key based on a variable
  2. If key already exists add new value to key
  3. If key does not exists create new key and add new value to it

Here is what I got and it has many issues:

if @agencyList.has_key?(domain)
    @agencyList[domain] << match
else
    @agencyList[domain] = match
end

Thanks!

2
  • Also, consider using the multimap gem. Then (assuming you use a Multimap instance for @agencyList) you'd use @agencyList[domain] = match to add an entry, in all cases. Commented Mar 21, 2014 at 3:13
  • There's a pretty strong convention in Ruby of only using snake_case for variable names. CamelCase is detected by the parser and is reserved for constants (class names and module names). Using camelCase with a lowercase beginning will confuse basically everybody. Commented Mar 21, 2014 at 3:16

2 Answers 2

4

Suppose your hash has values of Array type, and add new value to the array rather than replacing it. The follows can work:

@agency_list[domain] ||= []
@agency_list[domain] << match

Enjoy!

Sign up to request clarification or add additional context in comments.

2 Comments

...which you'll often see written (@agency_list[domain] ||= []) << match.
@CarySwoveland yeah.., it goes further.
1

Are the values of the keys arrays that you want to add the new value to, or just objects that you want to overwrite?

If they're arrays you want to add to, this should work;

if @agency_list.has_key?(domain)
  @agency_list[domain] << match
else
  # This way you can create the array and put the value in at the same time
  @agency_list[domain] = [match]
end

If they're just objects you want to overwrite, you don't even have to check if they key is there;

@agency_list[domain] = match

1 Comment

I don't want to overwrite. The problem is the value I add are all bunched into one element. I need them to be in separate elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.