arrays - Ruby Strings - Checking against a set of strings to match -
i trying check array of strings containing 1 or more matching strings.
currently doing using if statements - not nice, works - looking more ruby-like way this.
row[:datapoints].each |data| if data[:direction].include? "beusselstr" data[:image] = "category-1" end if data[:direction].include? "ostkreuz" data[:image] = "category-1" end if data[:direction].include? "westend" data[:image] = "category-2" end if data[:direction].include? "1)s gr" data[:image] = "category-3" end end instead of i'd store matching strings in array. make bit more complicated have different categories of matching terms own result actions (see category specific assignment of data[:image] value).
category_1_keywords = ["beusselstr","ostkreuz"] category_2_keywords = ["nefeld bhf","greifswalder","westend"] category_3_keywords = ["1)s gr"] imagecategories = {:category_1 => category_1_keywords,:category_2 => category_2_keywords,:category_3 => category_3_keywords} how filtering array (row[:datapoints]) using such matching array (imagecategories) like?
you want use array intersection operator & , check if it's empty.
if (data[:direction] & category_1_keywords).any? data[:image] = "category-1" end 4 if's in row though start looking time iterator:
keywords = { 'category_1' => ["beusselstr","ostkreuz"], 'category_2' => ["nefeld bhf","greifswalder","westend"], 'category_3' => ["1)s gr"] } data[:image] = keywords.find{|k,v| (data[:direction] & v).any?}[0]
Comments
Post a Comment