views:

81

answers:

2

I have a regular expression that returns multiple variables within a match. I am interested in the first non-null variable in a subset of indices within the match, so I am using

result = a[1] || a[3] || a[6] || ...

I would like to store the relevant indices in a configuration file along with the regular expression itself. What is the best shorthand notation that doesn't obfuscate the meaning?

+1  A: 

Use values_at to get an array which contains only the elements at the specified indices. Then use find {|x| x} to get the first element that is not nil or false.

result = a.values_at(*indices).find {|x| x}
sepp2k
The question said non-null, so assuming that means the bad values are `nil`, this could be simplified to `a.values_at(*indices).compact.first`.
glenn mcdonald
Does `compact` guarantee order persistence?
shmichael
+3  A: 

Another way:

result = [1,3,6].find {|x| a[x]}
Tumtu
It is actually supposed to be `a[ [1,3,6].find {|x| a|x|} ]` which is a little less aesthetic.
shmichael