簡體   English   中英

為什么從我的Ruby代碼中收到此“語法錯誤,意外的tIDENTIFIER”錯誤消息?

[英]Why do I get this “syntax error, unexpected tIDENTIFIER” error message from my Ruby code?

有人可以解釋一下為什么這個代碼不起作用嗎? 我還不太了解紅寶石,所以希望您能提供幫助。 它說我在puts multi[is]有語法錯誤:

syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '<' puts multi[is]

這是代碼:

        # multi = Array.new
        # multi[0] = Array.new(2, 'hello') 
        # # multi[1] = Array.new(2, 'world')
        # puts(multi[0])
        # puts(multi[1])

        multi = ['hest','hund','kat','fugl'] # names of animals
        for i in multi # convert to 
          is = i.to_i
          is++
          # puts(i. inspect
          puts multi[is]   # her i have error says  syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '<' puts
          multi[is]
        end


        food = Array.new # a new arry

        # 0 milk  names for food
        # 1 ost
        # 2 kod
        # 3 ris

is++是導致錯誤的一個。 只需將其寫is+=1 在ruby中沒有--++運算符。

直接來自文檔:

Ruby沒有前置/后置增減運算符。 例如,x ++或x--將無法解析。 更重要的是,++ x或--x將什么都不做! 實際上,它們表現為多個一元前綴運算符:-x == --- x == ----- x == ......要增加數字,只需寫x + = 1。

我通過一些修改重新編寫了您的代碼:

multi = ['hest','hund','kat','fugl'] # names of animals
index=-1
for name in multi
  p "#{name} at #{index+=1}"
end
# >> "hest at 0"
# >> "hund at 1"
# >> "kat at 2"
# >> "fugl at 3"

奧雅納(Arup)已經回答了這個問題,但是我希望在您的代碼中添加不符合其約定的Rubyish色調。

multi = ['hest','hund','kat','fugl'] # names of animals

multi.each_with_index do |m, i|
  puts "#{i+1} #{m}"
end

each_with_index是Ruby 枚舉器 ,它為您提供兩個塊變量,一個用於元素(此處為m ),另一個用於對應元素的索引(此處為i )。

繼續紅寶石。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM