1
\$\begingroup\$

I want to find the corresponding hash in an array from a string that contains a criterion defined in a hash of the array.

I do something like that :

types = [
 {key: 'type_1', criteria: ['type_1a', 'type_1b']},
 {key: 'type_2', criteria: ['type_2a', 'type_2b']},
 ...
]

def find_type(str)
  types.each do |type|
    type[:criteria].each do |criterion|
      return type if str =~ /#{criterion}/i
    end
  end
  nil
end

I'm sure it could be more ruby but don't find how...

\$\endgroup\$
5
\$\begingroup\$

The orthodox (and functional) approach in Ruby is:

def find_type(types, str)
  types.detect do |type|
    type[:criteria].any? do |criterion|
      str =~ /#{criterion}/i # or Regexp.new(criterion, "i")
    end
  end
end
\$\endgroup\$
  • \$\begingroup\$ To guard against the possibility that any of the hashes to not have the key :criteria, you may want to replace h[:criteria] with (h[:criteria] || []). \$\endgroup\$ – Cary Swoveland Apr 30 '14 at 5:21
  • \$\begingroup\$ You forgot that the method needs types as an argument. I'll be deleting this comment... \$\endgroup\$ – Cary Swoveland Apr 30 '14 at 5:22
  • \$\begingroup\$ I guess types was not really a local variable but something accessible by the method. Anyway, added as an argument. \$\endgroup\$ – tokland Apr 30 '14 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.