我正在使用Ruby 2.4。我有一个具有这样的值的数组
['1/ 8', '5 / 16', nil, '12 / 25', nil, '8/9']
我的问题是,当数组中的元素不是时nil
,我如何找出所有在"/"
?之后的唯一值?您可以假定数组中的所有值都是nil
或,"/"
后跟一定程度的空白,然后是数字。
如果我正确回答了您的问题,而您需要从以下途径提出8
(或'8'
?),请执行以下操作'1/ 8'
:
a = ['1/ 8', '5 / 16', nil, '12 / 25', nil, '8/9']
a.compact.each_with_object({}) do |str, hash|
hash[str] = str.split('/').last.split(' ').map(&:to_i).uniq
end
#=> {"1/ 8"=>[8], "5 / 16"=>[16], "12 / 25"=>[25], "8/9"=>[9]}
如果只需要获取uniq值:
values = a.compact.flat_map {|str| str.split('/').last.split(' ').map(&:to_i) }.uniq
#=> [8, 16, 25, 9]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句