Tag: 实例变量

在Ruby中,为什么在启动irb之后,foo.nil? 说未定义的错误,@ foo.nil? 给出“真实”和@@ wah.nil? 再次出错?

在Ruby 1.8.7和1.9.2中也是如此: $ irb ruby-1.8.7-p302 > foo.nil? NameError: undefined local variable or method `foo’ for # from (irb):1 ruby-1.8.7-p302 > @bar.nil? => true ruby-1.8.7-p302 > @@wah.nil? NameError: uninitialized class variable @@wah in Object from (irb):3 为什么实例变量的处理方式与局部变量和类变量不同?

控制器的所有操作的相同实例变量

我有一个rails控制器,定义了两个动作: index和show 。 我有一个在index action中定义的实例变量。 代码如下所示: def index @some_instance_variable = foo end def show # some code end 如何访问show.html.erb模板中的show.html.erb ?

ruby:类实例变量vs实例变量

我的想法是为来自java背景的人创建一个社区wiki,因为阅读了很多解释,直到我真正尝试了几件事并且拼图的各个部分开始找到他们的位置时,我无法理解任何事情。 但我首先需要确保我做对了。 从这样的背景来看,我发现@variable可能意味着两个非常不同的东西,这让我非常困惑。 这是一个例子: class Test @ins = “gah” def self.ins puts @ins end def initialize() @ins = “wtf?” end def ins2 puts @ins end end 据我所知,第一个@ins是表示类Test的对象的实例变量。 第二个@ins是Test类对象中的实例变量。 现在事情开始对我有意义了。 这里有几个例子: [14] pry(main)> test.ins2 wtf? 我们正在调用一个对象的方法,它返回对象的实例变量。 [15] pry(main)> test.ins NoMethodError: undefined method `ins’ for # 我们试图通过一个对象调用一个类方法,这个方法属于类,所以我们得到NoMethodError [16] pry(main)> Test.ins gah 我们正在调用一个类方法,因此它可以正确地看到类对象的实例变量。 [17] pry(main)> Test.ins2 NoMethodError: undefined […]

新手总数:ruby中的实例变量?

请原谅新的总体问题,但为什么@game_score总是为零呢? #bowling.rb class Bowling @game_score = 0 def hit(pins) @game_score = @game_score + pins end def score @game_score end end