Determining whether one array contains the contents of another array in ruby

前端 未结 11 1020
清歌不尽
清歌不尽 2021-02-09 03:06

In ruby, how do I test that one array not only has the elements of another array, but contain them in that particular order?

correct_combination = [1, 2, 3, 4, 5         


        
11条回答
  •  北恋
    北恋 (楼主)
    2021-02-09 03:48

    Maybe <=> is what you are looking for.

    Comparison—Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array

    a = [1, 2, 3, 4, 5]
    b = [1, 5, 8, 2, 3, 4, 5]
    c = [8, 10, 1, 2, 3, 4, 5, 9]
    
    puts a <=> b # => -1
    puts a <=> c # => -1
    puts a <=> a # => 0
    

    Update: nevermind, just noted it doesn't care about position.

    puts a <=> a.reverse # => -1
    

提交回复
热议问题