我有一個輸入數組的問題,嘗試在CodeWars上的Ruby挑戰。未定義的方法`split'for []:Array Ruby codewars「誰喜歡它?卡塔
以下是說明: 實現一個函數likes :: [String] - > String,它必須包含輸入數組,其中包含喜歡項目的人的姓名。它必須返回如例子中的顯示文本:
likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
我嘗試代碼是:
def likes(names)
arr = Array.[](names.split(/\W+/))
if arr.size == 0
var = "no one likes this"
return var
elsif arr.size == 1
return arr[0]+ " likes this "
elsif arr.size == 2
return arr[0] + "and #{arr[1]} likes this "
elsif arr.size == 3
return " #{arr[0]}, #{arr[1]} and #{arr[2]} likes this "
elsif arr.size >3
return "#{arr[0]}, #{arr[1]} and #{arr.size-1} likes this "
end
end
而這正是編譯回報:
`likes': undefined method `split' for []:Array (NoMethodError)
from `block in
'
from `block in describe'
from `measure'
from `describe'
from `
'
沒有名爲'split'爲陣的方法。 – vgoff
通過@vgoff擴展評論:您已經將數組傳遞給方法。如果'names'是一個由名稱列表組成的字符串,那麼您需要使用'#split'將它分割成一個數組。但是由於'names'是一個數組,你可以簡單地消除包含'#split'方法的代碼行,並在整個方法中用'names'代替'arr'。 – moveson
行結束符註釋以Ruby中的'#'開頭。 '//'不支持。 –