ruby - How many objects have the same attribute value? -
i have array of objects top , left attributes this:
[{top: 30, left: 20}, {top:50, left:10}, {..}] i trying find how many objects have approximate same top value. in case:
[{top: 10, left: 20}, {top:10, left:10}, {top: 10, left: 123}, {top:500, left:10}, {top:2, left: 50}, {top:2, left:400}] the method return 5 because there 3 objects have 10 top value , 2 objects have 2 top value. if there object doesn't share top value else, not taken account. not looking exact values, flexibility of 10% of difference on values {top:10, left:20} , {top:10.13, left:20} considered having same top. far, have this:
myarr.group_by { |x| x[:top] }.map { |k,v| [k, v.length] }.to_h but not take account margin error. not sure how change in order so.
depending on how want express "similar", this:
def count_similar(a, lower_bound, upper_bound) a.count { |h| h[:top] >= lower_bound && h[:top] <= upper_bound } end = [{top: 10, left: 20}, {top:10, left:10}, {top: 10, left: 123}, {top:500, left:10} , {top:2, left: 50}, {top:2, left:400}] count_similar(a, 1, 19) #=> 5
Comments
Post a Comment