Ruby中的普通变量与实例变量,有什么区别? [英] Normal Variables Vs Instance variable in Ruby, Whats the difference?

查看:40
本文介绍了Ruby中的普通变量与实例变量,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例 ruby​​ 类

Consider the following sample ruby class

class User
  def hello
    puts "hello"
  end
end

现在,进行初始化.有两种方式

now, for initialization. there are two ways

正常变量

1.9.3p125  > tr = User.new
 => #<User:0x98778c4>
1.9.3p125  > tr.hello
 Hello world
 => nil`

实例变量:

1.9.3p125 > @tr = User.new
 => #<User:0x9890f2c>
1.9.3p125 > @tr.hello
Hello world
 => nil

现在,在这两种情况下,它的工作原理相同.那么普通变量和实例变量有什么区别?

Now, in both cases it works the same. so what is the difference between normal variable vs instance variable?

推荐答案

普通变量仅在当前上下文中具有作用域;一个实例变量在类的一个实例中具有作用域.在您的情况下,他们感到困惑,因为上下文是 main,它充当 Object 的实例.

A normal variable has scope only within the current context; an instance variable has scope throughout one instance of a class. In your case they're confused because the context is main, which acts as an instance of Object.

考虑以下内容,这可能会使事情更清楚

Consider the following, which may make things clearer

class User
  def set_name
    @name = "Bob"
    surname = "Cratchett"
  end

  def hi
    puts "Hello, " + @name
  end

  def hello
    puts "Hello, Mr " + surname
  end
end

irb(main):022:0> u = User.new
=> #<User:0x29cbfb0>
irb(main):023:0> u.set_name
irb(main):024:0> u.hi
Hello, Bob
=> nil
irb(main):025:0> u.hello
NameError: undefined local variable or method `surname' for #<User:0x29cbfb0 @name="Bob">

这篇关于Ruby中的普通变量与实例变量,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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