0

I have a method that tries to parse a query into a a hash.

CONTACT_SEARCH_FIELDS = ['LastUpdate','Name','RecAdd','PhoneNumber','Tag_Group','FirstName','LastName','FamilyName','FamilyHead','ClientStatus','ContactType','ClientSource','TaxId']
CONTACT_SEARCH_OPERANDS = ['=','>','<','!=','Like','BeginsWith','IsEmpty']

def search (query, page = 1)
    body = [{}]*query.length
    query.each_with_index do |expr, i|
        body[i]["Field"] = CONTACT_SEARCH_FIELDS.index expr[0]
        body[i]["Operand"] = CONTACT_SEARCH_OPERANDS.index expr[1]
        body[i]["Value"] = expr[2]
    end
    return body
end

The method is called like this

search([["FirstName", "=", "John"], ["LastName", "=", "Smith"]])

The problem is that running this gives a very weird output.

search([["FirstName", "=", "John"], ["LastName", "=", "Smith"]])
=> [{"Operand"=>0, "Value"=>"Smith", "Field"=>6}, {"Operand"=>0, "Value"=>"Smith", "Field"=>6}]

I did some debugging and the problem is that all the hashes in the array are get set on every iteration.

I dont understand what is the reason behind this. I would also welcome any shorter or better versions of this code.

1 Answer 1

2

Change the line

body = [{}]*query.length

The above means, you are creating an Array, whose elements are same Hash objects.

Example :

a = [{}]*3 # => [{}, {}, {}]
a.map(&:object_id) # => [18499356, 18499356, 18499356]
a[0]["a"] = 2
a # => [{"a"=>2}, {"a"=>2}, {"a"=>2}]

to

body = Array.new(query.length) { {} }

But the above means, you are creating an Array, whose elements are different Hash objects.

Example :

a = Array.new(3) { {} } # => [{}, {}, {}]
a.map(&:object_id) # => [17643864, 17643852, 17643840]
a[0]["a"] = 2
a # => [{"a"=>2}, {}, {}]
Sign up to request clarification or add additional context in comments.

1 Comment

Does the first definition create n hashes which point to the same address in memory?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.