代码之家  ›  专栏  ›  技术社区  ›  alavni shubham

下面的程序打印变量的值。为什么?

  •  0
  • alavni shubham  · 技术社区  · 8 年前
    hello_world = 'Hello Ruby World' 
    
    def hello_world
      'Hello World' 
    end
    
    puts hello_world
    

    请解释为什么要打印变量的值?

    1 回复  |  直到 8 年前
        1
  •  4
  •   engineersmnky    8 年前

    如果编译器在同一范围内找到同名的变量和方法时有歧义,它将优先于该变量。

    若要显式调用该方法,请发送空parens ()

    hello_world = 'Hello Ruby World' 
    
    def hello_world
      'Hello World' 
    end
    
    puts hello_world()
    

    或者提供方法的显式接收器,在本例中,使用 self

    self.hello_world
    

    编辑 : AS sepp2k 建议在下面的评论中, self.hello_world 不能用红宝石( .rb 文件。尝试一下,您可以使用 send :

    send(:hello_world) #or
    method(:hello_world).call
    
    推荐文章