0
class Foobar
  def initialize
    self.placeHolder = ''
  end
end

bbq = Foobar.new

When I run the following code I receive a NoMethodError. This is very confusing to me, why would I not be able to have an empty instance variable? I know I can have an empty class variable but how come when I include self it gives me this error?

chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100

3 Answers3

3

Your code is trying to call the placeHolder= method, which your class doesn't have.

@placeHolder = ''

should work for you.

Or, you could add this line to your class:

attr_accessor :placeHolder

It will automatically create a getter and setter method for you. See this answer for a great explanation.


When you do someObject.someName in ruby, that always means call the someName method on someObject. (Now you can fake some other kinds of behaviors because you can define a method_missing method to handle when a method is called that doesn't exist.) So when you do self.someName that just means call the someName method on some instance of the class.

Community
  • 1
  • 1
JKillian
  • 18,061
  • 8
  • 41
  • 74
  • Ok cool. But why would self.identifier create a method at all? I come from Python background and that is how why we declare object variables there. Why would it automatically assume its a method? – chopper draw lion4 May 22 '14 at 23:51
  • Added a little bit more detail in the answer to hopefully cover your question – JKillian May 23 '14 at 04:57
2

You're attempting to call the instance method placeHolder= of the Foobar class. The Foobar class does not have this method, so it correctly gives you a NoMethodError. If you want to set an instance variable, the syntax for doing that is @placeholder = ''. If instead you wish to have an accessor method, you'll need to either write one yourself or include attr_accessor :placeHolder in the class body.

(Incidentally, it is idiomatic in Ruby to use snake_case rather than camelCase.)

Chuck
  • 234,037
  • 30
  • 302
  • 389
2

This is because attr_accessors aren't defined in class Foobar.

attr_accessor :placeholder
cvibha
  • 693
  • 5
  • 9