2017-03-02 50 views
1

我正在使用Ruby 2.4。除了數組中的一個索引外,如何掃描數組中的每個元素?我想這如何掃描除一個索引之外的數組的每個元素?

arr.except(2).any? {|str| str.eql?("b")} 

但得到了以下錯誤:

NoMethodError: undefined method `except' for ["a", "b", "c"]:Array 

,但顯然我在網上看關於「除」是大大誇大了。

+1

究竟做了你閱讀'除了',並在哪裏? Ruby數組沒有這樣的方法。 另外,在字符串上調用'.eql?'並不是非常習慣;你可以做'str ==「b」'。 –

+0

我發現了一篇文章,其中有人自己定義了這樣的方法,但即使在那裏它也是基於元素的值,而不是它的索引。 –

+1

[這是一個嗎? :)](https://coderwall.com/p/skzsoa/ruby-array-except) –

回答

2
arr.reject.with_index { |_el, index| index == 2 }.any? { |str| str.eql?("b") } 

說明:

arr = [0, 1, 2, 3, 4, 5] 
arr.reject.with_index { |_el, index| index == 2 } 
#=> [0, 1, 3, 4, 5] 

縮短你在做什麼:

arr.reject.with_index { |_el, index| index == 2 }.grep(/b/).any? 
#=> true 

繼@卡里的評論,另一種選擇是:

arr.each_with_index.any? { |str, i| i != 2 && str.eql?("b") } 
相關問題