Ruby 变量的默认值 [英] Default values of Ruby variables

查看:40
本文介绍了Ruby 变量的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道 ruby​​ 中变量的默认值.

I need to know the default values of variables in ruby.

Global Variables: nil
Instance Variables: ? 
Class Variables: ?
Local Variables: ?

我查看了这里,但我能找到的只是全局变量的值为零.

I looked here, but all I could find is that global variables have a nil value.

推荐答案

您在第一次赋值时分配了一个局部变量值:

You assign a local variable value at first assignment:

local = 1
local1 + local # NameError: undefined local variable or method `local1' for main:Object

类变量类似,如果不初始化就使用,会报错:

Class variables are similar, if you use them without initialization, you get an error:

class A
  @@a
end  
# NameError: uninitialized class variable @@a in A

类实例变量和类变量默认为nil:

Class instance variables and class variables are nil by default:

class A
  def self.a
    @a
  end  
  def a
    @a
  end  
end  

> A.a
#=> nil
> A.new.a
#=> nil

这篇关于Ruby 变量的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆