2017-09-11 59 views
-1

下面是一個代碼:Codefights字符串的隱式轉換成整數

def allLongestStrings(inputArray) 
    array = Array.new 
    inputArray.each do |i| 
     if inputArray[i].length == inputArray.max.length 
      array << inputArray[i] 
     end 
    end 
    return array 
end 

inputArray = ["aba", "aa", "ad", "vcd", "aba"] 

它說:「字符串到整數的隱式轉換」,我無法弄清楚。我究竟做錯了什麼?

+0

這是使用PHP思維的Ruby代碼。查看下面的[這個答案](https://stackoverflow.com/a/46164155/4265352),瞭解針對您的問題的Ruby解決方案。 – axiac

回答

2

錯誤是在這裏:

if i.length == inputArray.max.length # i instead of inputArray[i] 
    array << i 
end 

但我建議使用select:

input_array = ["aba", "aa", "ad", "vcd", "aba"] 
max_length = input_array.max.length 
input_array.select { |el| el.length == max_length } 
#=> ["aba", "vcd", "aba"]