nilanjan
nilanjan

Reputation: 679

how to use different conditions in a ruby hash select

I am trying to select a subset of a hash. Suppose I have a method which does this, e.g.,

def create_html (entities, low, high)
  entities
    .select{|k,v| v[:entity_count] < low and v[:community] == true}
    .sort_by{| k,v| v[:count]}.each do | k,v |
.....

I want to handle various conditions: assume a lower limit (low) and higher limit (high)

  1. count < low
  2. count > low and count < high
  3. count > high

I also want to use lte and gte. Is there an easy way to handle all the combinations in my select statement? Is there a better way to do this?

Upvotes: 0

Views: 512

Answers (1)

Ismael
Ismael

Reputation: 16730

I'm not sure I understood what you are trying to do. But you could just use a block to extract the condition.

def create_html (entities)
  entities
    .select{|k,v| yield(v[:entity_count], v[:community]) }
    .sort_by{| k,v| v[:count]}.each do | k,v |
.....

And then you could have all your conditions based on that field.

create_html(entities) { |count| count < low }
create_html(entities) { |count| count > low && count < high }
create_html(entities) { |count| count < low }

# Also with community == true
create_html(entities) { |count, community| count < low && community }

Upvotes: 1

Related Questions