Is this the best way to grab common elements from a Hash of arrays?

后端 未结 3 1730
[愿得一人]
[愿得一人] 2021-01-03 08:52

I\'m trying to get a common element from a group of arrays in Ruby. Normally, you can use the & operator to compare two arrays, which returns elements

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 09:39

    Behold the power of inject! ;)

    [[1,2,3],[1,3,5],[1,5,6]].inject(&:&)
    => [1]
    

    As Jordan mentioned, if your version of Ruby lacks support for &-notation, just use

    inject{|acc,elem| acc & elem}
    

提交回复
热议问题