English 中文(简体)
为什么这些方法不能解决问题?[副本]
原标题:Why aren t these methods resolving? [duplicate]
  • 时间:2011-05-30 03:24:14
  •  标签:
  • ruby

给定此代码:

class Something
  attr_accessor :my_variable

  def initialize
    @my_variable = 0
  end

  def foo
    my_variable = my_variable + 3
  end
end

s = Something.new
s.foo

我收到以下错误:

test.rb:9:in `foo : undefined method `+  for nil:NilClass (NoMethodError)
    from test.rb:14:in `<main> 

如果attr_accessor创建了一个名为my_variable(and..=)的方法,为什么tfoo找不到该方法?如果我将其更改为self.my_variable,它会起作用,但为什么?self不是默认的接收者吗?

最佳回答

你不是在那里调用方法,而是在引用你正在定义的同一个变量!这是鲁比的一个小陷阱。

最好是引用并设置实例变量:

@my_variable = @my_variable + 3

或更短:

@my_variable += 3

或者,您可以调用setter方法,如您所发现的(并且指向的抖动):

self.my_variable += 3

最后一个将调用attr_accessor定义的my_variable=方法,其中其他两个只修改一个变量。如果您这样做,您可以覆盖my_variable=来执行与传入值不同的操作:

def my_variable=(value)
  # do something here
  @my_variable = value
end

奖金

或者,您可以通过传递一组空参数来显式调用该方法:

my_variable = my_variable() + 3

这不是“Ruby方式”,但如果有一个同名的局部变量,仍然可以用这种方式调用方法,这一点仍然很有趣。

问题回答
my_variable = my_variable + 3

…是优先的局部变量赋值。

因此需要<code>self</code>-以便将其范围限定到对象。

如果在foo中执行my_variable,则会将其分配给局部变量my_variable,而不会调用方法my_variaable=

要根据需要分配值,您确实需要使用self

另请参阅此问题:为什么ruby setter需要在类中具有“self.”资格

我认为在这种情况下,变量的作用域仅在函数内,除非您在其前面加上<code>self@的code>。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签