代码之家  ›  专栏  ›  技术社区  ›  user160917

语法错误,意外的“=”

  •  1
  • user160917  · 技术社区  · 16 年前

    我在课堂上有以下内容

    def to_s
       i = 0
       first_line? = true
       output = ''
       @selections.each do | selection |
          i += 1
          if first_line?
             output << selection.to_s(first_line?)
             first_line? = false
          else
             output << selection.to_s
          end
          if i >= 5
             output << "\r"
             i = 0
          else (output << " $ ")
          end
       end
       return output
    end 
    

    SyntaxError: list2sel.rb:45: syntax error, unexpected '='
        first_line? = true
                     ^
    list2sel.rb:47: syntax error, unexpected keyword_do_block, expecting keyword_end
        @selections.each do | selection |
                           ^
    list2sel.rb:51: syntax error, unexpected '='
            first_line? = false
                         ^
    

    给什么,还要提前感谢,这让我发疯。

    4 回复  |  直到 16 年前
        1
  •  3
  •   Telemachus MrJames    16 年前

    变量名(下面有几个例外)只能包含字母、数字和下划线。(而且,它们必须以字母或下划线开头;不能以数字开头。)不能使用 ? !

    除此之外,还有一个 坚强的 Ruby中的一种惯例,即某物末尾的问号表示返回布尔值的方法:

    4.nil? # => returns false....
    

    所以即使你能用它,一个变量 first_line? 会把红宝石学家搞糊涂(然后惹恼)。他们希望这是一种测试某事物是否是某事物的第一行的方法(不管在上下文中这到底意味着什么)。

    变量名例外:

    • $ -例如。, $stdin 用于标准输入。
    • 实例变量以开头 @ -例如。 @name
    • 类变量以开头 @@ @@total 为了一节课
        2
  •  4
  •   Nakilon earlonrails    16 年前

    我想,你不能用“?”来命名变量最后。

        3
  •  3
  •   Mark Thomas    16 年前

    def to_s 
      output = ""
      @selections.each_with_index do | selection,line |  
        output << line==0 ? selection.to_s(true) and next : selection.to_s
        output << line % 5 ? " $ " : "\r"
      end 
      return output 
    end
    

    如果你不喜欢三元运算符(x?y:z)然后你可以让他们假设:

    def to_s 
      output = ""
      @selections.each_with_index do | selection,line |  
        if line==0
          output << selection.to_s(true)
        else
          output << selection.to_s
          if line % 5
            output << " $ "
          else
            output << "\r"
          end
        end
      end
      return output 
    end  
    
        4
  •  0
  •   Andrew Grimm Alex Wayne    16 年前

    non-ASCII versions 所以你可以把问号(以及一些形式的空格字符)放入变量名中。

    推荐文章