I have a rails app running on mongo. There is one Document that I need to query to perform a big calculation. The list of keys is huge like 50 plus.
I will be writing the calculation method in the model itself.
Since the number of keys is huge if I keep assigning the value of key to a local variable and use them, I would have to create 50 plus local variables. It would look like follows:
def get_score
record = Model.last
a1 = record['k1'],
a2 = record['k2'],
a3 = record['k3']
##---so--on 50 plus keys
#formulae. Where I will be using the a1...a50 variables to calculate.
end
This would make the method unnecessarily look huge and wont look efficient at all. Is there a way where I can add these keys into a file or hash and map and call those keys on the model at a once?
To avoid repeated hash accesses, you could do:
hash={'a1'=>1,'a2'=>2}
eval (1..2).map { |i| "@a#{i} = hash['a#{i}'];" }.join
This gives you @a1
and @a2
.
I can't figure out how to create local variables programmatically. You can write to a binding but not to the local scope it seems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.