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...

asked Apr 29, 2014 at 16:05
\$\endgroup\$
0

1 Answer 1

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
answered Apr 29, 2014 at 18:02
\$\endgroup\$
3
  • \$\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\$ Commented Apr 30, 2014 at 5:21
  • \$\begingroup\$ You forgot that the method needs types as an argument. I'll be deleting this comment... \$\endgroup\$ Commented Apr 30, 2014 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\$ Commented Apr 30, 2014 at 8:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.