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
oklas
  • 7,935
  • 2
  • 26
  • 42
blue-sky
  • 51,962
  • 152
  • 427
  • 752

4 Answers4

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
WarHog
  • 8,622
  • 2
  • 29
  • 23
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).

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
0

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

chown
  • 51,908
  • 16
  • 134
  • 170
ryudice
  • 36,476
  • 32
  • 115
  • 163
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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675