Erwin1
(Erwin)
February 27, 2011, 6:29pm
#1
given an Arra tags[]
I need to produce a resulting Hash as following ..
{ "$in" => [tags[0]], "$in" =>[tags[1], ...}
in which the key should be always the same and the value being an
Array
I tried this :
myHash = {}
tags.each do |tag|
h = {"$in" => [tag]}
myHash.merge!(h)
end
but the merge! is only changing the value ... (as the key is always
the same ..)
(there is no += as with Array class ...)
thanks for your feedback
By definition, a hash stores a single value for a given key. The
closest you'll get is to make the value an array of all the things for
the key in question.
Fred
11155
(-- --)
February 27, 2011, 7:06pm
#3
I agree with Frederick Cheung.
Your code will be like this :
myHashes = []
tags.each do |tag|
h = {"$in" => [tag]}
myHash << h
end
and myHashes will contains :
[{ "$in" => [tags[0]]}, {"$in" =>[tags[1]}, ...]
which myHashes is an array of hashes.
Hope this can help you
Erwin1
(Erwin)
February 27, 2011, 7:56pm
#5
this is to be used with MongoID as a criteria
criteria.where(:tags => { "$in" => [tags[0]], "$in"
=>[tags[1]] }).to_a
any suggestion with json structure ?
thanks Fred
this is to be used with MongoID as a criteria
criteria.where(:tags => { "$in" => [tags[0]], "$in"
=>[tags[1]] }).to_a
any suggestion with json structure ?
You can't repeat keys in a json hash either. What are you actually
trying to do?
Fred
Erwin1
(Erwin)
February 27, 2011, 9:49pm
#7
I need to write a Mongoid criteria
criteria.where(:tags => myStruct ).to_a
in which myStruct will have this structure { "$in" =>
[check_tags[0]], "$in" =>[check_tags[1]] , .. }
built from a check_tags Array
it's a sequence of .in criteria
I am checking if ALL of the elements of check_tags[] are included in a
Mongoid record Array field :tags
the simplest Mongoid criteria:
criteria.in(:tags => tags)
just perform a checking on ANY element included, not ALL
Erwin1
(Erwin)
February 27, 2011, 10:19pm
#8
Thanks fred .. found how to do it....
there is a specific criteria for it ( I did not fully understand when
reading it the first time...)
Criteria#all_in:
Matches if all values provided match, useful for doing exact matches
on arrays.
so writing :
criteria.all_in(:tags => tags ).to_a
did it ...
I'll try to give an eye to the underlaying Mongoid ruby code in charge
of doing that ....