0

I'm learning ruby dev coming from java and I dont understand why im getting below error. @test is a class variable so I should be able to output it ?

C:/Projects/RubyPlayground/Tester.rb:6:in `test': wrong number of arguments (ArgumentError)
    from C:/Projects/RubyPlayground/Tester.rb:6:in `testMethod'
    from C:/Projects/RubyPlayground/Tester.rb:10

source:

class Tester

  @test = "here"

  def testMethod()
    puts test
  end

  s = Tester.new()
  s.testMethod()

end
1
  • Please, take s object creation and call 'testMethod' out of class definition. Commented Oct 25, 2011 at 22:21

4 Answers 4

5

In this case @test became class instance variable and is associated with class object (not with class instance!). If you want @test behave like a java field, you have to use 'initialize' method:

class Tester
  def initialize
    @test = "here"
  end
  def testMethod
    puts @test
  end
end

s = Tester.new()
s.testMethod
Sign up to request clarification or add additional context in comments.

Comments

3

You're calling Kernel#test

test(int_cmd, file1 [, file2] ) → obj

Uses the integer <i>aCmd</i> to perform various tests on <i>file1</i>
(first table below) or on <i>file1</i> and <i>file2</i> (second table).

I'm kind of surprised such a method exists. I found where it was defined by using self.method(:test) in irb, thanks to the question How to find where a method is defined at runtime?

Your code wouldn't work even if you had attr_reader :test as @test is an instance variable of the Tester class object (an object of class Class), rather than an instance variable of the s instance object (an object of class Tester).

Comments

0

In your code you're calling the method Kernel#test with no arguments. However Kernel#test requires arguments, so you're getting an error telling you that you did not supply enough arguments (i.e. you didn't supply any at all).

If there would be no method test already defined in ruby, you would have gotten an error message telling you, you're trying to call an undefined method, which would probably have been less confusing to you.

Obviously it was not your intent to call a method named test - you wanted to access the instance variable @test. For that you have to write puts @test instead of puts test. However that still does not do what you want, because you've never set the variable @test on your new Test instance. You only set the @test variable once for the class. Instead you should set @test in the initialize method of Test.

Comments

0

It's "puts @test" .................................

1 Comment

Ok, but I would expect to see the value of @test instead of nil which is the curretn output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.