代码之家  ›  专栏  ›  技术社区  ›  Aaron Christiansen

RubyMine中代码完成的断言类型

  •  0
  • Aaron Christiansen  · 技术社区  · 6 年前

    确切地 任何函数将返回什么类型。

    然而,有时程序员知道。以下面的代码为例,它使用元编程来“混淆”代码完成:

    class Example
      define_method :foo do
        2 + 2
      end
    
      def bar
        foo_result = foo
      end
    end
    

    静态分析仪不知道这一点 foo 将永远是一个 Integer 我们知道,我只得到 BasicObject .

    enter image description here

    有没有一种方法可以告诉代码完成引擎我知道某个代码将是哪种类型的,这样我就可以得到更好的完成结果,而解释器只是忽略了这一点?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Aaron Christiansen    6 年前

    原来这是 部分 可以使用注释形式的“注释”,记录在: https://www.jetbrains.com/help/ruby/using-annotations.html

    可以向不明确的方法或变量添加类型,如下所示:

    # @return [String]
    def mystery_method
        # @type [Integer]
        foo = nil
    end
    

    不过,似乎不能使用这种方法创建全新的方法,例如元编程驱动的方法。