\$\begingroup\$
\$\endgroup\$
0
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...
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
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
-
\$\begingroup\$ To guard against the possibility that any of the hashes to not have the key
:criteria
, you may want to replaceh[:criteria]
with(h[:criteria] || [])
. \$\endgroup\$Cary Swoveland– Cary Swoveland2014年04月30日 05:21:25 +00:00Commented Apr 30, 2014 at 5:21 -
\$\begingroup\$ You forgot that the method needs
types
as an argument. I'll be deleting this comment... \$\endgroup\$Cary Swoveland– Cary Swoveland2014年04月30日 05:22:42 +00:00Commented 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\$tokland– tokland2014年04月30日 08:45:08 +00:00Commented Apr 30, 2014 at 8:45
lang-rb